java - @Autowired 与 New Keyword 和 Application context 创建对象的区别

标签 java spring

谁能告诉我这两者的区别

@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/

相关文章:

java - Maven 未能通过 JUnit Spring Controller 测试,但在 Eclipse 中工作正常

spring - 相当于Spring中的@ImplementedBy

spring - Spring什么时候在bean的生命周期中创建代理?

Spring Data Rest : how to register a custom conversionService with custom Converter<Entity, 资源>?

java - Spring Cloud数据流是否支持批处理

配置服务器上的 spring-cloud-starter-bus-kafka 设置

java - 是否可以将我的代码压缩成少于 3 行?

java - 通信 c 服务器和 java 客户端时出错

java - 如何在不耗尽内存的情况下使用 JDBC 将大量数据加载到文件中?

Java改变图像的饱和度