When I create my ApplicationContext
the myBean Constructors are used successfully.
But after creation the beans are null
using @Autowired
tag.
I though @Autowired
would replace getBean()
somehow? Am I getting this wrong?
Why do I need to call GetBean, when I already created my Beans (during ApplicationContext startup) and also Autowired them?
Here is what I have done so far:
Main:
@EnableAutoConfiguration
@Configuration
@ComponentScan("com.somePackage")
public class Main {
ApplicationContext ctx= new AnnotationConfigApplicationContext(AppConfig.class);
SomeBean myBean = ctx.getBean(SomeBean.class);
myBean.doSomething();//succeeds
AnyOtherClass aoc = new AnyOtherClass();//Nullpointer (see AnyOtherClass.class for details)
}
AnyOtherClass:
public class AnyOtherClass {
@Autowired
protected SomeBean someBean;
public AnyOtherClass(){
someBean.doSomething();//Nullpointer
}
AppConfig:
@Configuration
public class AppConfig {
@Bean
@Autowired
public SomeBean BeanSomeBean() {
return new SomeBean();
}
}
MyBean:
public class SomeBean {
public SomeBean (){}
public void doSomething() {
System.out.println("do Something..");
}
}
Note: Interface ApplicationContextAware
works fine but without @Autowired
. And I would really like to go with @Autowired
since it sounds more comfortable and less errorprone to me.