我有一个扩展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',并且假设你已经拥有了一个你所需要的事务管理器。 –
好的谢谢,的确我见过这样的代码。我应该只在抽象服务类或每个扩展类上做它,它应该也有注解?如果它处于课堂级别,是否意味着所有的方法都是事务性的,或者我还必须注释每个需要事务性的方法? –