事务的自我调用

马上该过年了,最近项目接近尾声,抽出时间搞了一下开发中困扰了我一段时间的一个问题:事务的自我调用;

项目中有一个方法由于逻辑比较复杂.多次调用本类的其他方法,出现了一个状况就是事务不准确了,其他方法中并没有生效;

由于时间紧,当时只是把逻辑集中到了一个方法中,造成了那个方法很大的冗余;现在不忙了就整理下那个方法;

写了一个小demo,基本配置:

	<context:component-scan base-package="com.ycgwl.kylin.**.service.impl">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
	<!-- 开启AOP -->
	<aop:config proxy-target-class="true" />

service:

	@Autowired
	private IUserService userService;
	
	@Test
	public void testProxyTargetClass() {
		userService.addUser();
	}

保证事务的自我调用的关键就是让切面生效,自我调用的时候切面不生效导致的事务失效;

我要保证的就是切面生效:

方案1:

	
	@Autowired
	private ApplicationContext context;
	
	private IUserService aopSelf;
	
	@PostConstruct       
	private void initLoad() {
		aopSelf = context.getBean(IUserService.class);
	}
	
	@Override
	public void addUser() {
		System.out.println(aopSelf   );
		System.out.println("current method : addUser()" );
	}

通过注入ApplicationContext中进行自我注入,

@PostConstruct是容器加载bean的构造函数结束之后执行该方法,用于初始化一些属性

方法2:

	<aop:config proxy-target-class="true" expose-proxy="true">

该注解的两个属性:

proxy-target-class :设置为true即设置容器的代理为cglib动态代理;

expose-proxy:设置是否暴漏代理对象,设置true的时候可以直接通过下面代码获取到代理对象:

@Override
	public void addUser() {
		System.out.println((UserServiceImpl)AopContext.currentProxy() );
		System.out.println("current method : addUser()" );
	}

该方法必须设置为true.否则报

java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
	

找不到代理对象的错误;

不说了,下面该重构我之前的代码了





猜你喜欢

转载自blog.csdn.net/alan_waker/article/details/79296944
今日推荐