谁能告诉我这两者的区别
@Autowired
CustomerService cService;
和
CustomerService cService=new CustomerService();
和
private static ApplicationContext applicationContext;
DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue");
最佳答案
执行 CustomerService cService=new CustomerService();
和其他两个语句的区别在于,在后面的两个语句中,Spring
将管理创建的生命周期对象及其依赖项,而在前一种情况下,您将必须管理对象的生命周期及其所需的所有依赖项。
执行 @Autowired CustomerService cService;
和 DefaultValueBean defaultValueBean = (DefaultValueBean) applicationContext.getBean("defaultValue");
的区别在于,在前一种情况下,Spring将根据 Autowiring 模式寻找一个 bean,在后面,您要求 Spring
寻找一个 id
配置为 defaultValue
你可以通过 Spring有关依赖注入(inject)的文档以获得更详细的解释。
关于java - @Autowired 与 New Keyword 和 Application context 创建对象的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915075/