Spring中添加自定义的yml文件,并用value读取值

Spring中添加自定义的yml文件,并用value读取值
方案A:
实现EnvironmentPostProcessor接口
并使用YamlPropertySourceLoader加载文件
例子:
public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {

private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Resource path = new ClassPathResource("com/example/myapp/config.yml");
    PropertySource<?> propertySource = loadYaml(path);
    environment.getPropertySources().addLast(propertySource);
}

private PropertySource<?> loadYaml(Resource path) {
    if (!path.exists()) {
        throw new IllegalArgumentException("Resource " + path + " does not exist");
    }
    try {
        return this.loader.load("custom-resource", path).get(0);
    }
    catch (IOException ex) {
        throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
    }
}

}

优点:Spring官方例子,比较安全
缺点:需要配置META-INF/spring.factories文件,key为EnvironmentPostProcessor的全路径,value为EnvironmentPostProcessorExample全路径

方案B:
使用PropertySource注解,需要自己实现factory方法
例子:
public class YamlSourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
factory.afterPropertiesSet();
Properties object = factory.getObject();
return new PropertiesPropertySource(“cumstom-properties”, object);
}
}
优点:比较方便
缺点:spring官方不是很推荐,启动过程会慢一点

方案C:
config类中bean
需要返回PropertySourcesPlaceholderConfigurer
例子:
@Bean
public PropertySourcesPlaceholderConfigurer load(){
YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources sources = new MutablePropertySources();
Resource resource = new ClassPathResource(“serviceconfig/service.yml”);
Resource appResource = new ClassPathResource(“application.yml”); // 如果不写这个 application的文件就失效了
try {
PropertySource load = yamlPropertySourceLoader.load(“service”, resource, null);
PropertySource loadApp = yamlPropertySourceLoader.load(“app”, appResource, null);
sources.addLast(load);
sources.addLast(loadApp);
configurer.setPropertySources(sources);

        return configurer;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
优点:网上大多数是这样写的
缺点:如果要多个yaml文件的话,需要把需要的都写在这里,这个方法会让spring默认的文件失效Spring中添加自定义的yml文件,并用value读取值

方案A:
实现EnvironmentPostProcessor接口
并使用YamlPropertySourceLoader加载文件
例子:
public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {

private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    Resource path = new ClassPathResource("com/example/myapp/config.yml");
    PropertySource<?> propertySource = loadYaml(path);
    environment.getPropertySources().addLast(propertySource);
}

private PropertySource<?> loadYaml(Resource path) {
    if (!path.exists()) {
        throw new IllegalArgumentException("Resource " + path + " does not exist");
    }
    try {
        return this.loader.load("custom-resource", path).get(0);
    }
    catch (IOException ex) {
        throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
    }
}

}

优点:Spring官方例子,比较安全
缺点:需要配置META-INF/spring.factories文件,key为EnvironmentPostProcessor的全路径,value为EnvironmentPostProcessorExample全路径

方案B:
使用PropertySource注解,需要自己实现factory方法
例子:
public class YamlSourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
factory.afterPropertiesSet();
Properties object = factory.getObject();
return new PropertiesPropertySource(“cumstom-properties”, object);
}
}
优点:比较方便
缺点:spring官方不是很推荐,启动过程会慢一点

方案C:
config类中bean
需要返回PropertySourcesPlaceholderConfigurer
例子:
@Bean
public PropertySourcesPlaceholderConfigurer load(){
YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
MutablePropertySources sources = new MutablePropertySources();
Resource resource = new ClassPathResource(“serviceconfig/service.yml”);
Resource appResource = new ClassPathResource(“application.yml”); // 如果不写这个 application的文件就失效了
try {
PropertySource load = yamlPropertySourceLoader.load(“service”, resource, null);
PropertySource loadApp = yamlPropertySourceLoader.load(“app”, appResource, null);
sources.addLast(load);
sources.addLast(loadApp);
configurer.setPropertySources(sources);

        return configurer;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
优点:网上大多数是这样写的
缺点:如果要多个yaml文件的话,需要把需要的都写在这里,这个方法会让spring默认的文件失效
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在 Spring Boot 取 YAML 文件可以使用注解 `@Value` 或者 `@ConfigurationProperties`。 使用 `@Value` 注解: ```java @Value("${property.name}") private String propertyName; ``` 使用 `@ConfigurationProperties` 注解: ```java @ConfigurationProperties(prefix = "property") @Data public class Property { private String name; } ``` 在 application.yml 文件配置相应的属性: ```yml property: name: value ``` 然后在应用程序通过注入 Bean 的方式使用即可。 ### 回答2: Spring Boot是一个用于构建独立的、生产级别的Spring应用程序的框架,它提供了许多便利的功能,其之一是yml文件。 首先,我们需要在Spring Boot项目添加YAML文件。YAML(YAML Ain't Markup Language)是一种简洁且易的数据序列化格式,通常用于配置文件。 在src/main/resources目录下创建一个名为application.yml文件。在该文件,我们可以使用键值对的形式来配置各种属性。 例如,我们可以配置服务器端口号: server: port: 8080 然后,我们需要创建一个类来yml配置文件的属性。可以使用@ConfigurationProperties注解将该类与yml文件的属性进行绑定。 ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "server") public class ServerProperties { private int port; public int getPort() { return port; } public void setPort(int port) { this.port = port; } } ``` 在上述示例,我们使用@ConfigurationProperties注解指定了yml文件的配置项前缀为"server",然后定义了一个整型属性port,通过对应的getter和setter方法可以获取和设置该属性的值。 最后,我们可以在其他组件或Bean使用该ServerProperties类来获取yml文件的属性值。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MyComponent { private final ServerProperties serverProperties; @Autowired public MyComponent(ServerProperties serverProperties) { this.serverProperties = serverProperties; } public void printServerPort() { int port = serverProperties.getPort(); System.out.println("Server port: " + port); } } ``` 在上述示例,我们通过构造函数注入了ServerProperties对象,并在printServerPort方法获取了yml文件配置的服务器端口号,然后打印出来。 这样,我们就可以通过Spring Bootyml文件的属性值了。Spring Boot会自动将yml文件的属性与@Component注解的类进行绑定,从而方便我们使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值