简体   繁体   中英

Understanding Spring4 annotation beans

First time using Spring with annotions. I'm trying to define a singleton bean like:

@Bean
public ActionProducer actionProducer() {
    return new ActionProducer();
}

But i feel like this is not a correct way to do since returns a "new" bean each time. Should i instead define like below?

@Bean
public ActionProducer actionProducer() {
    if (bean==null) 
        bean=new ActionProducer();
    return bean 
}

Thanks in advance.

For each @Configuration class, Spring will create a proxy which controls the calls to those @Bean methods. So if you have a @Bean method, which should create a singleton bean (which it does by default, if you don't specify another scope) the proxy will make sure, that the method is only called once to create the bean. All further calls are intercepted by the proxy and the already existing bean will be returned.
This way, you could even just call that bean method, if you have other beans in that class, which depend on it, without thinking about scopes, duplicate instances etc.:

@Bean
public AnotherClass anotherClass() {
    return new AnotherClass(actionProducer());
}

So don't work around the Spring functionality and just implement the method as following:

@Bean
public ActionProducer actionProducer() {
    return new ActionProducer();
}

From my knowledge, the @Bean is singleton yes, and therefor returning new ActionProducer(); is just fine. It will only be invoked by spring once at startup.

If ActionProducer is your own implementation, just annotate the class with @Component instead.

Default it is treated as singleton just as in the normal annotation way or xml way. If you want other scope then you can use scope annotation on the method.

Reference https://www.quora.com/Is-any-method-annotated-with-Bean-treated-as-Singleton-by-Spring-Framework

The @Bean annotation let you to define a Bean into the Spring application context. By Default Spring creates the beans as singletons. So this code will produce a singleton in Spring context

@Bean
public ActionProducer actionProducer() {
    return new ActionProducer();
}

But you need to access the bean through the Application context

applicationContext.getBean("myBeanName")

If you need an instance of your bean for each invocation, you need to define Prototype scope. It's the same, you need to access it through the Spring application context.

@Bean(scope=DefaultScopes.PROTOTYPE)
public ActionProducer actionProducer() {
    return new ActionProducer();
}

You can see more here http://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html

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