1. 程式人生 > >spring setter注入 構造器 順序

spring setter注入 構造器 順序


public class AwareBean implements BeanFactoryAware, BeanNameAware, ApplicationContextAware, InitializingBean {
    private String beanName;

    private ApplicationContext applicationContext;

    private BeanFactory beanFactory;

    @Override
    public void setBeanName(String beanName) {
        System.out.println("--Enter AwareBean.setBeanName(), beanName = " + beanName + "\n");
        this.beanName = beanName;
    }}
<bean id="awareBean" class="com.flynn.AwareBean">
        <property name="beanName" value="awareBean2"/>
    </bean>

上面setBeanName會執行2次 。先是setter注入然後是構造器注入

--Enter AwareBean.setBeanName(), beanName = awareBean2

--Enter AwareBean.setBeanName(), beanName = awareBean

 <bean id="awareBean" class="com.flynn.AwareBean">
      
    </bean>

構造器注入 ,只執行一次。

 

經過試驗得知,Spring注入Bean,例項化一個Bean的時候,順序如下:

1. 這個class的建構函式被執行;

2.Setter被執行;

3.如果這個class實現了InitializingBean(即implements InitializingBean)則,接下來執行public void afterPropertiesSet() throws Exception() 中的內容。