I have a code:
@Configuration
public class BeanSample {
@Bean(destroyMethod = "stop")
public SomeBean someBean() throws Exception {
return new SomeBean("somebean name1");
}
class SomeBean {
String name;
public SomeBean(String name) {
this.name = name;
}
public void stop() {
System.out.println("stop");
}
}
public static void main(String[] args) throws Exception {
BeanSample beanSample = new BeanSample();
SomeBean someBean1 = beanSample.someBean();
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"appContext.xml"});
SomeBean someBean2 = (SomeBean) appContext.getBean("someBean");
if (someBean1 == someBean2) System.out.println("OK");
}
}
I'm expecting, once I start app, the BeanSample.getSomeBean() then SomeBean is started to be available by 'someBean'.
Bu now I have an error: No bean named 'someBean' is defined
Actually, I dot not understand which app-context I should use to pick my beans up?
About @Configuration:
Any reasons, why I should use @Configuration annotation here? (with this one, my IDE highlights my classes as it were Spring-related then, so it should make sense )
-- OK: after I got an answer my code looks like this:
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext appContext = new AnnotationConfigApplicationContext(BeanSample.class);
SomeBean someBean2 = (SomeBean) appContext.getBean("someBean");
if (someBean2 != null) System.out.println("OK");
}
First, if you use the Java config, you have to instantiate your context like this:
new AnnotationConfigApplicationContext(BeanSample.class)
Second, the @Configuration
annotation doesn't make a bean out of the class that is annotated. Only the @Bean
methods are used to create beans.
If you want to have a BeanSample
bean too, you have to create another @Bean
method that creates one. But then again, why would you want that? I think the a @Configuration
class should only be used as the configuration container and not for anything else.
Third, the default bean names for @Bean
do not follow the conventions of property getters. The method names are used directly, meaning in your example, the bean would be named getSomeBean
and not someBean
. Change the method to this:
@Bean(destroyMethod = "stop")
public SomeBean someBean() throws Exception {
return new SomeBean("somebean name1");
}
Finally, the @Configuration
class should not be instantiated. Its methods only serve the purpose of creating the beans. Spring will then handle their lifecycle, inject properties and so on. In contrast, if you instantiate the class and call the methods directly, the returned objects will be just normal objects that don't have anything to do with Spring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With