简体   繁体   English

从另一个标注为Bean的方法中调用Bean方法

[英]Calling a bean method from another method annotated as Bean

I have two methods annotated with @Bean. 我有两个用@Bean注释的方法。 I am calling one @Bean annotated method from another. 我正在从另一个调用一个@Bean注释方法。 Does it mean it creates two beans of the same type? 这是否意味着它会创建两个相同类型的bean?

Here's my code: 这是我的代码:

@Configuration
@Import({BaseConfig.class})
public class TestConfig{

    @Autowired
    BaseConfig baseconfig;
    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public SampleTestClass sampleTest() {
        return new SampleTestClass(baseconfig.createNewBean());
    }

}

@Configuration
@Import(SomeClassConfig.class)
public class BaseConfig {

    @Autowired
    private int someAttribute;

    @Bean
    public SampleTest createNewBean() {
        return new SampleTest(someAttribute);
    }
}

No, it wouldn't. 不,不会。

SampleTest has a singleton scope which is the default, so even if you call the method "directly", Spring will make sure that there is only one instance per container. SampleTest具有默认的singleton作用域,因此,即使您直接调用方法,Spring也会确保每个容器只有一个实例。

No, it doesn't. 不,不是。 Spring automatically proxies @Configuration classes at runtime and decorates @Bean methods to provide the correct scope behavior. Spring在运行时自动代理@Configuration类,并修饰@Bean方法以提供正确的作用域行为。

However, in your case it would be cleaner not to tangle the two configurations unnecessarily. 但是,在您的情况下,不要不必要地纠缠这两种配置会更清洁。 Instead, you could do this: 相反,您可以这样做:

@Bean
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public SampleTestClass sampleTest(SampleTest dependency) {
    return new SampleTestClass(dependency);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM