AUTOWIRE_NO的作用

来源:互联网 发布:流星网络电视怎么注册 编辑:程序博客网 时间:2024/05/22 09:50

看公司框架里经常用到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 @EqualsAndHashCodepublic class People {    private Book book;}@Data @EqualsAndHashCode@Componentpublic 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 @EqualsAndHashCodepublic 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并不会影响他的作用


0 0
原创粉丝点击