【发布时间】:2019-02-14 01:00:54
【问题描述】:
我通过如下代码创建 Spring ApplicationContext:
public static AnnotationConfigWebApplicationContext startContext(String activeProfile,
PropertySource<?> propertySource, Class<?>... configs) {
AnnotationConfigWebApplicationContext result = new AnnotationConfigWebApplicationContext();
if (propertySource != null) {
result.getEnvironment().getPropertySources().addLast(propertySource);
}
if (activeProfile != null) {
result.getEnvironment().setActiveProfiles(activeProfile);
}
result.register(configs);
result.refresh();
return result;
}
在测试类中我这样称呼它:
@RunWith(SpringJUnit4ClassRunner.class)
class FunctionalTest {
private ApplicationContext appContext;
@BeforeEach
void init() {
appContext = Utils.startContext("functionalTest", getPropertySource(),
BaseConfig.class, MyApplication.class, StorageTestConfig.class);
}
}
它工作正常,没有问题。
现在我正在尝试做同样的事情,但通过注释:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BaseConfig.class, MyApplication.class, StorageTestConfig.class},
loader = AnnotationConfigContextLoader.class)
@ActiveProfiles("functionalTest")
@PropertySource(value = "classpath:test-context.properties")
class FunctionalTest {
@Autowired
private ApplicationContext applicationContext;
...
}
这根本不起作用。 applicationContext 不是自动装配的,bean 也是来自配置。你能说我可能做错了吗?
为什么我想从代码切换到注释:我希望能够从配置中自动装配 bean。现在(以上下文创建的代码方式)我应该在测试方法中编写类似appContext.getBean("jdbcTemplate", JdbcTemplate.class) 的内容。如果能写出来就好了
@Autowired
private JdbcTemplate jdbcTemplate;
这将起作用:)
【问题讨论】:
-
您能否发布一个堆栈跟踪,并在您尝试使用注释时抛出异常?
-
没有抛出异常,只是没有填充@Autowired字段(ApplicationContext和JdbcTemplate(来自StorageTestConfig类的bean))。它们仍然为空
-
如何运行测试?你的 JUnit 版本是什么?
-
Junit5,我通过点击运行按钮在 Idea Intellij IDE 中运行测试
标签: spring-annotations applicationcontext spring-bean spring-config springjunit4classrunner