最近需要在同一個類里面調用標注@Async 異步調用。所以,注入的類需要是代理對象。但注入的卻不是代理對象
package tk.mybatis.springboot.service; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; /** * 測試依賴注入 * 異步注解不生效問題 測試 * <p> * 創建代理對象 方法 * org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary(java.lang.Object, java.lang.String, java.lang.Object) * <p> * 問題點:為什么@lazy注入的就是代理對象 (理解錯誤,看着是一個代理對象,但那個對象是錯誤的) * 為什么@PostConstruct 方法是在代理對象執行后執行的,但獲取的bean卻不是代理對象? * * * * @author liuzh * @since 2016-01-31 21:42 */ @Slf4j @Service public class TestAsyncService extends AbstractProduce implements ApplicationContextAware, InitializingBean { @Autowired private TestAsyncService testAsyncService; /** * InitDestroyAnnotationBeanPostProcessor */ @PostConstruct public void init() { TestAsyncService bean = applicationContext.getBean(TestAsyncService.class); System.out.println(bean.getClass().getName()); //testAsyncService = bean; } @Autowired public TestAsyncService(@Lazy TestAsyncService testAsyncService) { System.out.println(testAsyncService.getClass().getName()); if (this.testAsyncService != null) { System.out.println(this.testAsyncService.getClass().getName()); } this.testAsyncService = testAsyncService; } @Override public void test() { TestAsyncService bean = applicationContext.getBean(TestAsyncService.class); System.out.println(bean.getClass().getName()); System.out.println("======== test {}" + Thread.currentThread().getName()); testAsyncService.testAsync(); } @Async public void testAsync() { System.out.println("=========async test {}" + Thread.currentThread().getName()); System.out.println("async lll"); } ApplicationContext applicationContext; @Override public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() throws Exception { TestAsyncService bean = applicationContext.getBean(TestAsyncService.class); // testAsyncService = bean; } }
我們常用的在本類中注入自己 是循環依賴 可以用 如何解決循環依賴處理
但這上面的方式注入的都是注入的沒有進行AOP增強的原始類。
看起來@Lazy的是增強的,但仔細一看不是。
@PostConstruct 最后執行但還不是代理類
這個方法是增強創建代理類的方法。打斷點是最最后執行的