我决定编写一个不带“ @SpringBootTest”的“组件”测试。如果设置了@Enableconfigurationproperties,则@Сontexthierarchy不会缓存bean。
当我同时运行“ TestOne”和“ TestTwo”时,HelloWorld组件将初始化两次,这可以通过“ init666”中字符串的两次出现来证明。可能是什么问题呢?
TestOne
@RunWith(SpringRunner.class)
@EnableConfigurationProperties
@ContextHierarchy({
@ContextConfiguration(classes = TestConfiguration.class),
@ContextConfiguration(classes = TestOneConfiguration.class)
})
public class TestOne {
@Autowired
HelloWorld helloWorld;
@Test
public void test () {
}
}
TestOneConfiguration
@Configuration
public class TestOneConfiguration {
}
测试二
@RunWith(SpringRunner.class)
@EnableConfigurationProperties
@ContextHierarchy({
@ContextConfiguration(classes = TestConfiguration.class),
@ContextConfiguration(classes = TestTwoConfiguration.class)
})
public class TestTwo {
@Autowired
HelloWorld helloWorld;
@Test
public void test () {
}
}
TestTwoConfiguration
@Configuration
public class TestTwoConfiguration {
}
测试配置
@Configuration
public class TestConfiguration {
@Bean
HelloWorld helloWorld () {
return new HelloWorld();
}
你好,世界
@Component
public class HelloWorld {
public HelloWorld() {
System.out.println("init666");
}
}
截图:double appearance of the string in "init666"
附言@SpringBootTest不能使用
最佳答案
目前,我找到了唯一的解决方案:
摆脱@Enableconfigurationproperties
从application.yml加载属性
TestOne
@RunWith(SpringRunner.class)
@EnableConfigurationProperties
@ContextHierarchy({
@ContextConfiguration(classes = TestConfiguration.class,
initializers = TestContextInitializer.class),
@ContextConfiguration(classes = TestOneConfiguration.class)
})
public class TestOne {
@Autowired
HelloWorld helloWorld;
@Test
public void test () {
}
}
TestContextInitializer
public class TestContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
try {
Resource resource = applicationContext.getResource("classpath:application.yml");
YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
PropertySource<?> yamlTestProperties = sourceLoader.load("applicationProperties", resource, null);
applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
String[] profiles = applicationContext.getEnvironment().getProperty("spring.profiles.active").replaceAll(" ", "").split(",");
applicationContext.getEnvironment().setActiveProfiles(profiles);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
通过环境雕刻必填字段
@Autowired
private Environment environment;
public Someclass somemethod() {
Someclass someclass = new Someclass();
String someField = environment.getProperty("someField");
someclass.setSomeField(someField);
return someclass;
}
如果有的话,我会很高兴看到这些建议。
谢谢!