spring boot properties类型安全以及自动装配bean
- 将要配置的属性名写入到application.properties文件中,例如:
reids.host=10.1.10.22
redis.port=6319
redis.other.user=jdw
redis.other.pass=jdw_001
redis.host-url=localhost
- 增加类型安全的配置java文件RedisProperties.java文件,代码如下:
package com.jiangdengwei.redis;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* @author jackychiang
*/
@ConfigurationProperties(prefix = "redis") //配置项前缀
public class RedisProperties {
private String host;
private Integer port;
//这里是支持host-url类型的配置
private String hostUrl;
private Other other;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public String getHostUrl{
return this.hostUrl;
}
public void setHostUrl(String hostUrl){
this.hostUrl = hostUrl;
}
public void setPort(Integer port) {
this.port = port;
}
public Other getOther{
return this.other;
}
public void setOther(Other other){
this.other = other
}
//这里是支持other层级配置项
public static class Other{
private String user;
private String pass;
public String getUser{
return this.user;
}
public void setUser(String user){
this.user = user;
}
public String getPass(){
return this.pass;
}
public void setPass(String pass){
this.pass = pass;
}
}
}
- 增加自动装配类RedisAutoConfiguration.java
package com.jiangdengwei.redis;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
/**
* @author jackychiang
*/
@Configuration //指定为配置类
@ConditionalOnClass(Jedis.class) //只有在存在Jedis.class的时候才有效
@EnableConfigurationProperties(RedisProperties.class) //引入RedisProperties.class类型安全的配置
public class RedisAutoConfiguration {
@Bean //标记bean
@ConditionalOnMissingBean //只有在容器中没有名字为jedis的时候才会产生jedis的bean
public Jedis jedis(RedisProperties redisProperties) {
return new Jedis(redisProperties.getHost(), redisProperties.getPort());
}
}
- 增加Redis配置启用开关注解
package com.jiangdengwei.redis;
import org.springframework.context.annotation.Import;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(RedisAutoConfiguration.class)
public @interface EnableRedis {
}
- 使用方法
package com.jiangdengwei.device;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableCaching
@EnableScheduling
@SpringBootApplication
@EnableRedis
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ps: 小白刚写博客,欢迎大家指教