springboot 构造方法里获取不到@Value注入的值
有很多情况,我们想要在构造方法里使用@Value注入的值,却发现值为null,未注入
@Component
public class User {
@Value("userName")
private String userName;
@Value("password")
private String password;
private String[] box;
public User() {
box = new String[]{userName, password};
System.out.println(box[0]);
}
}
解决方法:在构造方法的参数里使用@Value注入
@Component
public class User {
private String[] box;
public User(@Value("userName") String userName,
@Value("password") String password) {
box = new String[]{userName, password};
System.out.println(box[0]);
}
}