在Spring App中调用未使用的Bean

我的Spring应用程序中有一些奇怪的行为,这是Java Spring Boot应用程序的结构:


在包装中com.somethingsomething.packageA,我有2个文件


首先是ParentA.java


package com.somethingsomething.packageA;


import javax.annotation.PostConstruct;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


@Component

public class ParentA {

    @Autowired

    private ChildA childA;


    public ChildA getChildA() {

        return childA;

    }


    @PostConstruct

    public void ParentAPostConstruct() {

        System.out.println("ParentA PostConstruct were called");

    }

}

第二个是ChildA.java


package com.somethingsomething.packageA;


import org.springframework.stereotype.Component;


@Component

public class ChildA {

    public ChildA() {

        System.out.println("ChildA were called");

    }

}

然后在package下com.somethingsomething.packageB,我也有两个类似的文件。


首先是ParentB.java


package com.somethingsomething.packageB;


import javax.annotation.PostConstruct;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;


@Component

public class ParentB {

    @Autowired

    private ChildB childB;


    public ChildB getChildB() {

        return childB;

    }


    @PostConstruct

    public void ParentBPostConstruct() {

        System.out.println("ParentB PostConstruct were called");

    }

}

第二个是ChildB.java


package com.somethingsomething.packageB;


import org.springframework.stereotype.Component;


@Component

public class ChildB {

    public ChildB() {

        System.out.println("ChildB were called");

    }

}

但是在这种情况下ChildA were calledParentA PostConstruct were called没有被假设要记录。

那么,为什么会发生这种特殊的行为呢?这是Spring的默认行为吗?


慕哥6287543
浏览 195回答 3
3回答

互换的青春

是的,这是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()。我建议您阅读此书,以更深入地了解范围。

江户川乱折腾

为什么会这样呢?当您启动Spring应用程序时,ApplicationContext将通过组件扫描您的应用程序并在上下文中注册所有带Spring注释的bean进行初始化。这样可以根据需要注入它们。这是Spring的默认行为吗?是的。您可以通过将组件扫描配置为仅根据需要查看指定的软件包来更改此行为(尽管此用例很少且相差很远)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java