2016-06-28 83 views
12

我在春季有一个关于自动布线订单和@PostConstruct逻辑的问题。例如下面的演示代码,我有一个主弹簧引导类:春季自动装配订单和@PostConstruct

@SpringBootApplication 
public class Demo1Application { 

    @Autowired 
    BeanB beanb; 

    public static void main(String[] args) { 
     SpringApplication.run(Demo1Application.class, args); 
    } 
} 

和2 @Service定义:

@Service 
public class BeanB { 

    @Autowired 
    private BeanA beana ; 

    @PostConstruct 
    public void init(){ 
     System.out.println("beanb is called"); 
    } 

    public void printMe(){ 
     System.out.println("print me is called in Bean B"); 
    } 
} 

@Service 
public class BeanA { 

    @Autowired 
    private BeanB b; 

    @PostConstruct 
    public void init(){ 
     System.out.println("bean a is called"); 
     b.printMe(); 
    } 
} 

,我有以下的输出:

豆被称为

打印我在Bean B中调用

beanb被称为


我的问题是自动装配是如何发生的一步一步像上面的​​场景?
以及如何printMe()方法beanb被调用,而不是先调用其@PostConstruct

回答

8

下面应该是可能的序列

  1. beanb开始变得自动连接
  2. 期间Beanb类的初始化,beana开始被自动连接
  3. 一旦beana被创建beana的@PostConstructinit()被称为
  4. Inside init()System.out.println("bean a is called");被称为
  5. 然后b.printMe();被调用导致System.out.println("print me is called in Bean B");执行
  6. 具有beana完成@PostConstructbeanbinit()被调用
  7. 然后System.out.println("beanb is called");被调用

在理想情况下同样可以通过在蚀调试器可更好地观察到的。

Spring reference manual说明如何解决循环依赖关系。这些bean首先被实例化,然后被注入彼此。

+1

[链接](https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/beans。 html#beans-dependency-resolution)到循环依赖解析。 –

3

你的答案是正确的,正如你在你的问题中所示。

现在获取符号的概念@Autowired。全部@Autowired对象初始化并在类加载完成后加载到内存中。

现在,这里是你的SpringBootApplication

@SpringBootApplication 
public class Demo1Application { 
    @Autowired 
    BeanB beanb; // You are trying to autowire a Bean class Named BeanB. 

在这里,在上述控制台应用程序,你必须写尝试自动装配和注入BeanB类型的对象。

现在,这里是你的BeanB

@Service 
public class BeanB { 

    @Autowired 
    private BeanA beana ; 

BeanB类,你正在试图注入这也是在您的控制台项目中定义BeanA类的对象定义。

因此,在您的Demo1Application中注入类BeanB的对象必须注入类BeanA的对象。 Now BeanA类对象首先被创建。

现在,如果你看到你的类BeanA

@Service 
public class BeanA { 

    @Autowired 
    private BeanB b; 

    @PostConstruct // after Creating bean init() will be execute. 
    public void init(){ 
     System.out.println("bean a is called"); 
     b.printMe(); 
    } 
} 

这样的定义,@PostContruct注释是要执行注射对象BeanA方法绑定后。

所以,执行流程将..

System.out.println("bean a is called"); 
System.out.println("print me is called in Bean B"); 
System.out.println("beanb is called"); 
相关问题