Spring Boot 之注解@Component @ConfigurationProperties(prefix = "sms")
从spring-boot开始,已经支持yml文件形式的配置,@ConfigurationProperties的大致作用就是通过它可以把properties或者yml配置直接转成对象
例如:
配置文件: sms.url=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX sms.appkey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX sms.secret=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX sms.signName=XXXXXXXXXXXXXXXXXXXXXXXXXXX sms.tplCode=XXXXXXXXXXXXXXXXXXXXXXXXXXXX sms.type=normal
JAVA代码: @Component @ConfigurationProperties(prefix = "sms") public class SmsSettings { private String url =""; private String appkey =""; private String secret =""; private String signName =""; private String tplCode =""; private String type =""; private String open =""; private String tplCode2 =""; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getAppkey() { return appkey; } public void setAppkey(String appkey) { this.appkey = appkey; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public String getSignName() { return signName; } public void setSignName(String signName) { this.signName = signName; } public String getTplCode() { return tplCode; } public void setTplCode(String tplCode) { this.tplCode = tplCode; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getOpen() { return open; } public void setOpen(String open) { this.open = open; } public String getTplCode2() { return tplCode2; } public void setTplCode2(String tplCode2) { this.tplCode2 = tplCode2; } }
通过注解@ConfigurationProperties来配置redis
@Configuration @EnableAutoConfiguration public class RedisConfig { @Bean @ConfigurationProperties(prefix="spring.redis.poolConfig") public JedisPoolConfig getRedisConfig(){ JedisPoolConfig config = new JedisPoolConfig(); return config; } @Bean @ConfigurationProperties(prefix="spring.redis") public JedisConnectionFactory getConnectionFactory(){ JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setUsePool(true); JedisPoolConfig config = getRedisConfig(); factory.setPoolConfig(config); return factory; } @Bean public RedisTemplate<?, ?> getRedisTemplate(){ RedisTemplate<?,?> template = new StringRedisTemplate(getConnectionFactory()); return template; } }