转自:https://blog.youkuaiyun.com/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;
Spring Boot 配置 Redis
本文介绍了如何在 Spring Boot 中使用 properties 和 yaml 文件配置 Redis 的方法。通过示例展示了如何利用 @Value 和 @ConfigurationProperties 注解将配置文件中的属性注入到 Java Bean 中。
4万+

被折叠的 条评论
为什么被折叠?



