当前位置: 代码迷 >> 综合 >> SpringBoot 注解@ConfiguretionProperties
  详细解决方案

SpringBoot 注解@ConfiguretionProperties

热度:22   发布时间:2023-10-25 16:13:52.0

        很多情况下我们会把配置文件的信息,读取并自动封装成实体类,我们在代码里面使用就不用每次使用的时候去@Value,这时候我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类。

application.yml 配置信息:

spring:redis:password: ys_123clusterNodes: 10.108.10.46:6379expireSeconds: 120commandTimeout: 10000pool:maxActive: 5000maxIdle: 30minIdle: 5maxWait: 3000maxAttempts: 1

我们可以定义一个实体类在装载配置文件信息:

package com.example.redis.redis;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;import java.util.HashMap;
import java.util.Map;@Component
@ConfigurationProperties(prefix = "spring.redis", location = "classPath:/config/application.yml")//1.5版本之前有使用location属性指定配置文件
@PropertySource("classPath:/config/application.yml")//1.5版本之后去除了location属性,需要使用@PropertySource注解
public class RedisProperties {private int    expireSeconds;private String clusterNodes;private String password;private int    commandTimeout;private Map<String,Integer> pool = new HashMap<>();public int getExpireSeconds() {return expireSeconds;}public void setExpireSeconds(int expireSeconds) {this.expireSeconds = expireSeconds;}public String getClusterNodes() {return clusterNodes;}public void setClusterNodes(String clusterNodes) {this.clusterNodes = clusterNodes;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public int getCommandTimeout() {return commandTimeout;}public void setCommandTimeout(int commandTimeout) {this.commandTimeout = commandTimeout;}public Map<String, Integer> getPool() {return pool;}public void setPool(Map<String, Integer> pool) {this.pool = pool;}
}

我们还可以把@ConfigurationProperties还可以直接定义在@bean的注解上,这是bean实体类就不用@Component和@ConfigurationProperties了

package com.example.redis;import com.example.redis.redis.RedisProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableCaching
public class RedisDemoApplication {public static void main(String[] args) {SpringApplication.run(RedisDemoApplication.class, args);}@Bean@ConfigurationProperties(prefix = "com.example.demo")public RedisProperties people() {return new RedisProperties();}
}

调用

@Autowired RedisProperties conn;public String test(){String password = conn.getPassword();     return "hello task !!";
}