I am fairly new to Annotation Driven Spring which got introduced after Spring 2.5. I have been fairly comfortable with the XML based configuration and I have never had any problems getting beans to AutoWire using XMl approach of loading the Spring Container. Things were so cool in the XML world but then I turned to the Annotation Ville and now I have a quick question for people here: Why would my beans won't autowire? here are the classes that I have created:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.myspringapp.MyBean;
import com.myspringapp.MySpringAppConfig;
public class TestConfig {
@Autowired
private static MyBean myBean;
public static void main(String[] args) {
new AnnotationConfigApplicationContext(MySpringAppConfig.class);
System.out.println(myBean.getString());
}
}
The above is the standard java class which invokes AnnotationConfigApplicationContext class. I was under the impression that once the "MySpringAppConfig" class is loaded I would have reference to the myBean aurowired property and hence would be able to call getString method on it. However, I am always getting null and hence NullPointerException.
package com.myspringapp;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String getString() {
return "Hello World";
}
}
Above is the component MyBean which is fairly simple to understand and below is the Configuration class:
package com.myspringapp;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MySpringAppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
Note: I am able to get the reference to bean if I use (MyBean)ctx.getBean("myBean"); but I dont want to use getBean method.