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的作用

原文地址:https://www.cnblogs.com/liran123/p/13932418.html