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:
Second, the
@Configurationannotation doesn’t make a bean out of the class that is annotated. Only the@Beanmethods are used to create beans.If you want to have a
BeanSamplebean too, you have to create another@Beanmethod that creates one. But then again, why would you want that? I think the a@Configurationclass should only be used as the configuration container and not for anything else.Third, the default bean names for
@Beando not follow the conventions of property getters. The method names are used directly, meaning in your example, the bean would be namedgetSomeBeanand notsomeBean. Change the method to this:Finally, the
@Configurationclass 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.