(1)@Value注解
格式:@Value("${XXX[:defaultValue]}")
作用:从配置文件中读取配置,第一个冒号后面的为默认值,默认值可不写
备注1:在使用@Value的类上,好像得有@Configurable注解,@Value才能被解释 - 待验证
备注2:@Value注解的变量,不能用statis 或 final修饰,不能在类加载阶段就初始化,否则变量的值为null,原理不懂
据说,可以用 下面这种方式来给static变量赋值: - 未测试
@Component
public class GlobalValue {
public static String DATABASE;
@Value("${mongodb.db}")
public void setDatabase(String db) {
DATABASE = db;
}
}
参考:https://www.cnblogs.com/zhouj-happy/p/6248798.html
(2)@ConfigurationProperties
格式:@ConfigurationProperties(prefix = "XXX")
作用:读取配置文件
备注1:这个注解,貌似可以在类初始化的时候就读取配置
备注2:需要实现getter /setter 方法
例:
@ConfigurationProperties(prefix = "x.kafka.producer")
public class KafkaProducerConfigProperties() {
private String bootstrapServer = "127.0.0.1:9092";
// getter setter
}
会读取 x.kafka.producer.bootstrapServer ,默认值是"127.0.0.1:9092"??
不常用注解:
(1)@Profile
格式:@Profile("XXX")
作用:设置哪个环境下的配置文件生效,相当于:spring.profiles.active配置
备注:任何@Component或@Configuration注解的类,都可以用@Profile标记
例:
@Configuration
@Profile("prod")
public class ProductionConfiguration () {
// do something
}
相当于:spring.profiles.active = prod