【发布时间】:2016-03-18 13:02:33
【问题描述】:
我对 Java Spring IoC 还很陌生,这是我的问题
我有一个 FactoryConfig 类,其中包含所有 bean 和注释 @Configuration 和 @ComponentScan,如下所示。
import org.springframwork.*
@Configuration
@ComponentScan(basePackages="package.name")
public class FactoryConfig {
public FactoryConfig() {
}
@Bean
public Test test(){
return new Test();
}
//And few more @Bean's
}
我的 Test 类有一个简单的 Print 方法
public class Test {
public void Print() {
System.out.println("Hello Test");
}
}
现在在我的主类中,我创建了 FactoryConfig 的 ApplicationContentext。 (我希望工厂配置中的所有@Beans 都将被初始化。但是,当我使用@Autowired 访问Test 类时它返回null
我的主要课程
public class Main {
@Autowired
protected static Test _autoTest;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ApplicationContext context =
new AnnotationConfigApplicationContext(FactoryConfig.class);
FactoryConfig config = context.getBean(FactoryConfig.class);
config.test().Print();
// _autoTest.Print(); <--- Im getting NULL Pointer Ex here
}
}
@Autowire 和使用对象/bean 的正确方法是什么?任何更清晰的解释将不胜感激。
【问题讨论】:
-
@Autowired和其他注解只能作用于 Spring 处理的对象。 Spring 不处理您的 Main 类。 Spring 可以做很多事情,但它并不神奇,它会在完全独立的类/对象实例中注入一些东西。