AUTOWIRE_NO的作用

看公司框架裏經常用到AutowireCapableBeanFactory.autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck)方式獲得Bean


對於第二個參數,有時候用的AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, 有時候AutowireCapableBeanFactory.AUTOWIRE_NO


今天特地研究了一下。


AutowireCapableBeanFactory.AUTOWIRE_NO

	/**
	 * Constant that indicates no externally defined autowiring. Note that
	 * BeanFactoryAware etc and annotation-driven injection will still be applied.
	 * @see #createBean
	 * @see #autowire
	 * @see #autowireBeanProperties
	 */
	int AUTOWIRE_NO = 0;

先看一下這個說明。

這裏其實已經說的比較明確了,不會對當前Bean進行外部類的注入,但是BeanFactoryAware和annotation-driven仍然會被應用

就是說Bean裏面加了@Autowired的@Resource這類的依然會有作用


AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE

	/**
	 * Constant that indicates autowiring bean properties by type
	 * (applying to all bean property setters).
	 * @see #createBean
	 * @see #autowire
	 * @see #autowireBeanProperties
	 */
	int AUTOWIRE_BY_TYPE = 2;

會按照Bean Type進行property的注入


Example

@Data @EqualsAndHashCode
public class People {

    private Book book;
}

@Data @EqualsAndHashCode
@Component
public class Book {

    private String name;
}

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//        People people = (People) context.getBean(People.class);
        AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
        People people = (People) beanFactory.autowire(People.class, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
        System.out.println(people.getBook());
    }

最終的結果是

Book(name=null) 即使在People裏面並沒有@Autowired Book


    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//        People people = (People) context.getBean(People.class);
        AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
        People people = (People) beanFactory.autowire(People.class, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
        System.out.println(people.getBook());
    }

最終的結果是

null

說明確實自動不會注入外部類

但是如果我們加上@Autowried


@Data @EqualsAndHashCode
public class People {

    @Autowired private Book book;
}

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
//        People people = (People) context.getBean(People.class);
        AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
        People people = (People) beanFactory.autowire(People.class, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
        System.out.println(people.getBook());
    }
最終的結果是

Book(name=null)


Conclusion

AutowireCapableBeanFactory的autowireMode只作用Bean中沒有被@Autowired @Resource等annotation修飾的properties

如果有@Autowired等修飾,autowireMode並不會影響他的作用


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章