文章目录
SpringBoot @PropertySource加载yum空值问题
SpringBoot 版本:.2.x.x
加载.yum文件,需要自定义工厂
1. 自定义工yum解析工厂
- DefaultPropertySourceFactory
public class DefaultPropertySourceFactory implements PropertySourceFactory {
public DefaultPropertySourceFactory() {
}
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
}
}
- YamlConfigFactory
public class YamlConfigFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = name != null ? name : resource.getResource().getFilename();
if (!resource.getResource().exists()) {
return new PropertiesPropertySource(sourceName, new Properties());
} else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
Properties propertiesFromYaml = loadYml(resource);
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
} else {
return super.createPropertySource(name, resource);
}
}
private Properties loadYml(EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
2. 整合代码
2.1 msg_cn.yml
cn:
promptMsg:
100001: "参数或者是列表参数必须为数字!"
businessMsg:
100001: "登录账号已存在!"
2.2 MsgEn.java
/**
* Component与ConfigurationProperties
* ConfigurationProperties prefix 解析
**/
@Component
@PropertySource(value = "classpath:/templates/language/msg_cn.yml", encoding = "UTF-8", factory = YamlConfigFactory .class)
@ConfigurationProperties(prefix = "en")
@Data
public class MsgEn {
/**
* 相关业务提示的中英日文翻译
*/
Map<String, String> promptMsg;
}
2.3 单元测试
@SpringBootTest(classes = Application.class)
@RunWith(SpringRunner.class)
public class MsgTest {
@Autowired
private MsgEn msgEn;
@Test
public void testMsgEn() {
System.out.println(msgEn.toString());
}
}
3. 添加依赖包
解决linux启动报错:java.lang.NoClassDefFoundError: org/yaml/snakeyaml/Yaml
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>