Spring Boot使用@ConfigurationProperties加载配置文件

Spring Boot开发中,一般会使用@Value注解和@ConfigurationProperties注解来加载配置信息

  • @Value(需要配合@Component):该注解的执行在java运行初始化的最后
  • @ConfigurationProperties:该注解初始化的时机是,凡是引用到该类的就会触发该注解

简单示例

(1)配置文件

1
2
3
4
spring:
redis:
host: 192.168.10.10
port: 6379

(2)配置类

1
2
3
4
5
6
7
@Data
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig {
private String host;
private String port;
}

注:字段必须包含Setter方法

(3)初始化

1
2
3
4
5
6
7
8
9
10
11
12
@Slf4j
@Component
public class AppInit {
@Autowired
private RedisConfig redisConfig;

@Bean
public void initRedis() {
log.info("Redis Host: " + redisConfig.getHost());
log.info("Redis Port: " + redisConfig.getPort());
}
}

静态引用

@ConfigurationProperties只会调用非静态的set方法,如需通过静态变量方式直接调用,需将Setter定义为非静态方法

(1)配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfig {
public static String host;
public static String port;

public void setHost(String host) {
RedisConfig.host = host;
}

public void setPort(String port) {
RedisConfig.port = port;
}
}

(2)初始化

1
2
3
4
5
6
7
8
9
@Slf4j
@Component
public class AppInit {
@Bean
public void initRedis() {
log.info("Redis Host: " + RedisConfig.host);
log.info("Redis Port: " + RedisConfig.port);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :