简体   繁体   中英

Calling a bean method from another method annotated as Bean

I have two methods annotated with @Bean. I am calling one @Bean annotated method from another. Does it mean it creates two beans of the same type?

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.

No, it doesn't. Spring automatically proxies @Configuration classes at runtime and decorates @Bean methods to provide the correct scope behavior.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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