最近写SpringBoot项目,因为有一些配置需要在线程中使用,准备通过添加Listener的方式实现配置文件的获取,在写单元测试的时候,发现Listener为启用,进过尝试,解决了,方法如下:
Listener类:
public class PropertyListener implements ApplicationListener<ContextRefreshedEvent> {
private static final LoggerLOGGER = LoggerFactory.getLogger(PropertyListener.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
Environment env = (Environment) contextRefreshedEvent.getApplicationContext()
.getBean("environment");
String fileName ="application.properties";
Map map =new HashMap<>();
getProperties(fileName, map);
if (env.getActiveProfiles() !=null && env.getActiveProfiles().length >0) {
fileName ="application-" + env.getActiveProfiles()[0] +".properties";
getProperties(fileName, map);
}
PropertyUtil.getInstance(map, fileName);
}
private void getProperties(String fileName, Map map) {
try {
Resource resource =new ClassPathResource(fileName);
InputStream is = resource.getInputStream();
Properties ps =new Properties();
ps.load(is);
ps.forEach((key, value) -> {
map.put(String.valueOf(key), value ==null ?null : String.valueOf(value));
});
}catch (IOException e) {
LOGGER.error("读取配置文件异常:", e);
}
}
}
单元测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {
@Test
public void testParam() {
Param param = ParamsUtil.getParam("xxxx");
System.out.println(param.toJson());
}
}
方法一:通过在单元测试类上添加@Import注解实现:
此时,单元测试类如下:
@RunWith(SpringRunner.class)
@SpringBootTest
@Import(PropertyListener.class)
public class SpringBootApplicationTests {
@Test
public void testParam() {
Param param = ParamsUtil.getParam("xxxx");
System.out.println(param.toJson());
}
}
方法二:通过给Listener类添加@Component注解,将其交给spring管理,也能实现,而且更方便,常规启动项目也能使用,非常方便,推荐方式:
@Component
public class PropertyListener implements ApplicationListener<ContextRefreshedEvent>
网友评论