我有一个通过factory-method创建的spring,我还需要使用@Transactional工具。所以,当我创建它时,如下所示:
<bean id="myBean" class="pack.age.MyBean" factory-method="create">
<constructor-arg ref="someBean" />
</bean>哪里
public class MyBean implements MyInterface{
private final SomeBean someBean;
public static MyInterface create(SomeBean someBean){
MyBean retVal = new MyBean(someBean);
//Create a thread and run it.
//Do some other job that doesn't suit for constructor
}
private MyBean(SomeBean someBean){
this.someBean = someBean;
}
}现在,当我试图将bean注入到阳极bean中时:
public class MyAnotherBean{
private MyInterface myInterface;
public boid setMyInterface(MyInterface myInterface){
this.myInterface = myInterface;
}
}宣布为
<bean id="myAnotherBean" class="pack.age.MyAnotherBean">
<property name="myInterface" ref="myBean" />
</bean>注入实际的myBean实例,而不是代理。因为它不是代理,所以我不能使用Spring @Transactional工具。
如何在通过静态factory-method构造对象时注入代理
发布于 2016-01-26 13:23:56
在这种情况下,仅在bean声明下启用事务注释就可以了:
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- (this dependency is defined somewhere else) -->
<property name="dataSource" ref="dataSource"/>
</bean>但是,如果没有,可以尝试以声明方式启用事务:
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- ensure that the above transactional advice runs for any execution
of an operation defined by the MyInterface interface -->
<aop:config>
<aop:pointcut id="myBeanOperation" expression="execution(* x.y.service.MyInterface.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="myBeanOperation"/>
</aop:config>https://stackoverflow.com/questions/35014463
复制相似问题