为了账号安全,请及时绑定邮箱和手机立即绑定

在Spring App中调用未使用的Bean

在Spring App中调用未使用的Bean

慕哥6287543 2021-04-15 22:23:09
我的Spring应用程序中有一些奇怪的行为,这是Java Spring Boot应用程序的结构:在包装中com.somethingsomething.packageA,我有2个文件首先是ParentA.javapackage com.somethingsomething.packageA;import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class ParentA {    @Autowired    private ChildA childA;    public ChildA getChildA() {        return childA;    }    @PostConstruct    public void ParentAPostConstruct() {        System.out.println("ParentA PostConstruct were called");    }}第二个是ChildA.javapackage com.somethingsomething.packageA;import org.springframework.stereotype.Component;@Componentpublic class ChildA {    public ChildA() {        System.out.println("ChildA were called");    }}然后在package下com.somethingsomething.packageB,我也有两个类似的文件。首先是ParentB.javapackage com.somethingsomething.packageB;import javax.annotation.PostConstruct;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class ParentB {    @Autowired    private ChildB childB;    public ChildB getChildB() {        return childB;    }    @PostConstruct    public void ParentBPostConstruct() {        System.out.println("ParentB PostConstruct were called");    }}第二个是ChildB.javapackage com.somethingsomething.packageB;import org.springframework.stereotype.Component;@Componentpublic class ChildB {    public ChildB() {        System.out.println("ChildB were called");    }}但是在这种情况下ChildA were called并ParentA PostConstruct were called没有被假设要记录。那么,为什么会发生这种特殊的行为呢?这是Spring的默认行为吗?
查看完整描述

3 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

是的,这是Spring的默认行为。在应用程序启动时@Component,无论是否使用它们,都将创建带有注释的所有Bean 。

applicationContext.getBean(ParentB.class)然后,该调用仅返回已创建的Bean。

要回答您的编辑: 默认情况下,Spring Bean是Singletons,因此,每个总是只有一个Bean实例applicationContext。这是Control Inversion,这意味着Spring处理对象实例化,而不是您。

具有Prototype范围的Bean可以具有多个对象实例,并且可以由您实例化。(通过致电applicationContext.getBean(ParentA.class))。这类似于做类似的事情ParentA a = new ParentA()

我建议您阅读此书,以更深入地了解范围。


查看完整回答
反对 回复 2021-04-28
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

为什么会这样呢?

当您启动Spring应用程序时,ApplicationContext将通过组件扫描您的应用程序并在上下文中注册所有带Spring注释的bean进行初始化。这样可以根据需要注入它们。

这是Spring的默认行为吗?

是的。您可以通过将组件扫描配置为仅根据需要查看指定的软件包来更改此行为(尽管此用例很少且相差很远)。


查看完整回答
反对 回复 2021-04-28
  • 3 回答
  • 0 关注
  • 194 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信