Reputation: 351
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.
Upvotes: 0
Views: 4253
Reputation: 5269
The only way i know is to autowire a static field is to use a setter. But this will also not work in your case because Spring needs to process the object, but the TestConfig
class is not processed in your code. If you want to inject dependencies into TestConfig
, you can to define it as a bean:
public class MySpringAppConfig {
@Bean
public TestConfig testConfig() {
return new TestConfig();
}
.....
Then get it via:
TestConfig tc = (TestConfig) ctx.getBean("testConfig");
Then Spring can inject myBean
, by using the setter method.
Upvotes: 1