我有一個擴展AbstractService類的服務列表。該AbstractService持有DAO(可以稱之爲 「庫」),並具有用於DAO中的getter/setter:將XML配置到JavaConfig:繼承和bean依賴關係
/**
* @param <T> Entity type
* @param <K> Entity ID type
* @param <S> DAO type
*/
public abstract class AbstractService<T, K extends Serializable, S extends BaseDAO<T, K>> implements BaseService<T, K> {
private S dao;
public S getDAO() { return dao; }
public void setDAO(S dao) { this.dao = dao; }
// Then common methods to all my services, using the DAO, for instance
@Override
public Optional<T> findOne(K key) throws DataException {
return Optional.ofNullable(dao.findOne(key));
}
}
服務例如:
@Service
public class EmployeeServiceImpl extends AbstractService<Employee, Integer, EmployeeDAO> implements EmployeeService {
// Some specific methods to that service
}
的相關DAO(我使用Spring數據JPA):
public interface EmployeeDAO extends BaseDAO<Employee, Integer> {
}
擴展
@NoRepositoryBean
public interface BaseDAO<T, K extends Serializable> extends JpaRepository<T, K> {
}
順便說一句,我在添加註釋@Service
和@NoRepositoryBean
,同時移動到JavaConfig。
我的舊XML配置爲:
<bean id="com.xxx.service._AbstractService" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="com.xxx.dao._TxManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED,-com.xxx.DataException</prop>
<prop key="update*">PROPAGATION_REQUIRED,-com.xxx.DataException</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-com.xxx.DataException</prop>
</props>
</property>
</bean>
<bean id="com.xxx.service.EmployeeService" parent="com.xxx.service._AbstractBO">
<property name="target">
<bean class="com.xxx.service.EmployeeServiceImpl">
<property name="DAO" ref="com.xxx.dao.EmployeeDAO"/>
</bean>
</property>
</bean>
第一個問題,什麼是注入通用的DAO和使用JavaConfig辦理服務繼承的正確方法?
第二個問題,如何將關於事務(com.xxx.service._AbstractBO)的XML片段轉換爲JavaConfig?
這裏是我到目前爲止,2類:
@Configuration
@ComponentScan("com.xxx.service")
public class SpringConfig {
}
和Persistence配置
@Configuration
@EnableJpaRepositories("com.xxx.repository")
@EnableTransactionManagement
public class PersistenceConfig {
/* Here so far I defined the DataSource, the EntityManagerFactory,
the PlatformTransactionManager and the JpaVendorAdapter */
}
預先感謝您的時間!
不要嘗試轉換事務代碼,而是轉移到「@ Transactional」。用@ Transactional註釋你的'@ Service'並添加'@ EnableTransactionManagement',並且假設你已經擁有了一個你所需要的事務管理器。 –
好的謝謝,的確我見過這樣的代碼。我應該只在抽象服務類或每個擴展類上做它,它應該也有註解?如果它處於課堂級別,是否意味着所有的方法都是事務性的,或者我還必須註釋每個需要事務性的方法? –