我通过如下代码创建 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;
这将起作用:)