(转)Spring boot 切换配置文件到yaml

转自:https://blog.csdn.net/github_34560747/article/details/52085628

在spring boot 中,我们可以通过properties或者yaml文件来为应用程序添加自定义的配置信息。以redis的配置信息为例:

    spring.redis.host=127.0.0.1  
    spring.redis.port=6379  
    spring.redis.timeout=5000  

 可以在redis.properites文件中编写如上信息,然后在redisconfig类中通过@PropertySource(value="classpath:redis.property")来注入配置文件信息,然后通过如下方式注入到bean的对应的属性中

    @Value("spring.redis.host")  
      private String host;  
      @Value("spring.redis.port")  
      private int port;  
      @Value("spring.redis.timeout")  
      private int timeout; 

 但这种方式还是过于累赘,实际上我们可以通过引入yaml文件(类似于json的结构)进行配置,在新建spring boot 项目时会自动引入snakeyaml,从而自动实现对yaml的支持。我们只需要进行如下配置即可:

application.yaml

redis:  
      host: 127.0.0.1  
      port: 6379  
      timeout: 5000 

 新建一个RedisSettings的bean:

    @Component  
    @Data  
    @ConfigurationProperties(prefix = "redis")  
    public class RedisSettings {  
      private String host;  
      private int port;  
      private int timeout;  
      
    }  

 最后在使用的入口注入即可

    @Autowired  
     private RedisSettings redisSettings;  

  

猜你喜欢

转载自jameskaron.iteye.com/blog/2422747