SpringBoot @PropertySource加载yum空值问题

SpringBoot @PropertySource加载yum空值问题

SpringBoot 版本:.2.x.x
加载.yum文件,需要自定义工厂

1. 自定义工yum解析工厂

  1. 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);
    }
}
  1. 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值