I create Spring ApplicationContext via code like the following:
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;
}
In test class I call it like that:
@RunWith(SpringJUnit4ClassRunner.class)
class FunctionalTest {
private ApplicationContext appContext;
@BeforeEach
void init() {
appContext = Utils.startContext("functionalTest", getPropertySource(),
BaseConfig.class, MyApplication.class, StorageTestConfig.class);
}
}
It works fine, no problems.
Now I'm trying to do the same but via annotations:
@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;
...
}
And this doesn't work at all. applicationContext
is not autowired, beans from configurations too. Can you please say me that possibly I do wrong?
Why I want to switch from code to annotations: I want to be able to autowire beans from configs. Now (in code way of context creation) I should write something like appContext.getBean("jdbcTemplate", JdbcTemplate.class)
in test methods. It will be great if I will be able to write
@Autowired
private JdbcTemplate jdbcTemplate;
and this will work :)