SpringBoot 2 动态加载 自定义 Properties

发布时间 2023-09-21 16:02:19作者: 啊哈咧
YML文件配置

  public static void initializeYml() throws IOException {
YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
factoryBean.setResources(new ClassPathResource("test.properties"));
factoryBean.afterPropertiesSet();
Properties properties = factoryBean.getObject();

ConfigurationPropertySource propertySource = new MapConfigurationPropertySource(properties);
Binder binder = new Binder(propertySource);

SutpcSsoProperties config = binder.bind("sutpc.sso.client.SUTPC-SSO", SutpcSsoProperties.class).get(); // same prefix as @ConfigurationProperties
System.out.println(config);
}


properties文件配置

  public static void initializeProperties() throws IOException {
PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();

factoryBean.setLocation(new ClassPathResource("test.properties"));
// factoryBean.setLocation(new InputStreamResource(Files.newInputStream(Paths.get("E:\\work_spaces\\git_repo\\sae-framework\\web-alone\\web-alone-sso\\src\\main\\resources\\test.properties"))));
factoryBean.afterPropertiesSet();
Properties properties = factoryBean.getObject();

ConfigurationPropertySource propertySource = new MapConfigurationPropertySource(properties);
Binder binder = new Binder(propertySource);

SutpcSsoProperties config = binder.bind("sutpc.sso.client", SutpcSsoProperties.class).get(); // same prefix as @ConfigurationProperties
System.out.println(config);

}