【发布时间】:2013-06-16 13:46:52
【问题描述】:
我对在 Spring 2.5 之后引入的 Annotation Driven Spring 相当陌生。我对基于 XML 的配置相当满意,而且我从来没有遇到过使用加载 Spring 容器的 XMl 方法将 bean 加载到 AutoWire 的任何问题。 XML 世界里的东西很酷,但后来我转向了 Annotation Ville,现在我有一个快速的问题要问这里的人们:为什么我的 bean 不会自动装配?这是我拥有的类创建:
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());
}
}
以上是调用 AnnotationConfigApplicationContext 类的标准 java 类。我的印象是,一旦加载了“MySpringAppConfig”类,我就会引用 myBean aurowired 属性,因此可以对其调用 getString 方法。但是,我总是得到 null,因此得到 NullPointerException。
package com.myspringapp;
import org.springframework.stereotype.Component;
@Component
public class MyBean {
public String getString() {
return "Hello World";
}
}
上面是MyBean组件,比较容易理解,下面是Configuration类:
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();
}
}
注意:如果我使用 (MyBean)ctx.getBean("myBean");但我不想使用 getBean 方法。
【问题讨论】:
-
@Autowire可以在 Spring managed Beans 中 Autowire Spring managed Beans。但是TestConfig不是Spring管理的! -
所以你的意思是我把这个 PSVM 类作为一个 JUnit 测试类并有 RunWith ( SpringJUnit....) 类?会由 Spring 管理吗?
-
Peter 我能够将这个类作为测试类运行,并且 JUnit 已通过,这意味着 myBean 属性确实已自动装配,并且我能够断言 getString 方法。现在我想知道当我将以下代码添加到类时它究竟有什么不同:@ContextConfiguration(classes=MySpringAppConfig.class) @RunWith(SpringJUnit4ClassRunner.class)