1. 程式人生 > 實用技巧 >spring 注入的bean不是代理物件

spring 注入的bean不是代理物件

最近需要在同一個類裡面呼叫標註@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 最後執行但還不是代理類

這個方法是增強建立代理類的方法。打斷點是最最後執行的

Spring迴圈依賴-earlySingletonObjects的作用