gpt4 book ai didi

java - 如何通过工厂方法创建事务代理?

转载 作者:行者123 更新时间:2023-12-01 10:32:29 24 4
gpt4 key购买 nike

我有一个通过工厂方法创建的 spring bean,我还需要使用@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 注入(inject)另一个 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>

注入(inject)实际的myBean实例,不是代理。由于它不是代理,因此我无法使用 Spring @Transactional 设施。

通过静态工厂方法构造对象时如何注入(inject)代理?

最佳答案

在这种情况下,只需在 beans 声明下启用事务注释就可以了:

<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>

关于java - 如何通过工厂方法创建事务代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35014463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com