【问题标题】:Can we create Bean and an object using new keyword at the same time?我们可以同时使用 new 关键字创建 Bean 和对象吗?
【发布时间】:2021-03-18 07:51:35
【问题描述】:
public class UserInterface{
public static void main(String args[]){

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

AbcClass abc = applicationContext.getBean(AbcClassImpl.class); 

AbcClass cde = new AbcClassImpl();
}
}

只是想知道如果我们已经为此创建了 Bean,是否可以使用 new 关键字创建。

【问题讨论】:

  • 你可以。但如果您通过 new 关键字创建对象,则自动装配在其中不起作用。如果您需要多个 bean 实例,则应查看原型范围
  • @Jens 谢谢,知道了。是的,这就是为什么我在尝试使用“cde”对象访问 Autowired 类的方法时得到 NullPointerException。

标签: java spring spring-boot dependency-injection


【解决方案1】:

是的,您可以,但是自定义实例化对象将缺少 spring 提供给 bean 的注入或依赖注入。

当然,最好遵循框架的原则。也就是说,避免手动实例化“bean”。

【讨论】:

  • 是的,知道了。我只是在尝试我们是否也可以使用 new 关键字创建它并且它是否具有完整的功能。但是当我尝试使用“cde”对象访问 Autowired 类的方法时得到 NullpointerException。谢谢!!
猜你喜欢
  • 2012-08-24
  • 1970-01-01
  • 2012-03-07
  • 1970-01-01
  • 2018-07-03
  • 2023-03-19
  • 1970-01-01
  • 2010-12-25
相关资源
最近更新 更多