接手一个任务开发预警邮件需求,计划将邮件信息(hostName,用户名,密码,发送方,接受方等)设置为可配置变量,配置在配置中心,使用@Value注解获取配置,如下:
@Value("${warning.email.hostName}")
private String hostName;
@Value("#{'${warning.email.receivers}'.split(',')}")
private List receivers;
@Value("${warning.email.userName}")
private String userName;
@Value("${warning.email.passWord}")
private String passWord;
@Value("${warning.email.sendFrom}")
private String sendFrom;
以上为正确配置方式,发生错误的情况是将这些变量全部声明为了静态变量,导致取值全部为空:
@Value("${warning.email.hostName}")
private static String hostName;
上网查询了下使用@Value的注意事项:
1、不能作用于静态变量(static);
2、不能作用于常量(final);
3、不能在非注册的类中使用(类需要被注册在spring上下文中,如用@Service,@RestController,@Component等);
4、使用这个类时,只能通过依赖注入的方式,用new的方式是不会自动注入这些配置的。
https://www.cnblogs.com/yanl55555/category/1574819.html