Springboot使用@value获取配置文件参数

发布时间 2023-09-19 09:15:27作者: 種瓜得豆

使用@value获取yml参数值

@Value("${value}") // 多级使用 . 连接  例:${value.value}
private String value;

@value获取不到值的情况

// 错误1:使用了static或者final修饰value
private static String value;
private final String value;

// 错误2:类没有加上@Component(或者@Service等)
@Component // 遗漏
class TestValue(
	@Value("${value}")
	private String value;
)

// 错误3:类被new新建了实例,没有使用@Autowired
@Component
class TestValue{
	@Value("${value}")
	private String value;
}
    
class Test{
	...
	TestValue teatValue = new TestValue();
}

// 错误4:与@AllArgsConstructor 注解同时使用
// 错误3的正确方式
class Test{
	@Autowired
	TestValue teatValue
}