作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我看到 @Value
注释应该可以解决问题,而不是在构造函数中使用 Properties
。
它在我的另一个实现中工作,但在这里它不工作
Controller :
@Autowired
private Customer customer;
我的类(class)
@Service
public class Customer {
/** The soap GW endpoint. */
@Value("${soapGWEndpoint}")
private String soapGWEndpoint;
/** The soap GW app name. */
@Value("${soapGWApplName}")
private String soapGWAppName;
/** The soap GW user. */
@Value("${generic.user}")
private String soapGWUser;
/** The soap GW password. */
@Value("${generic.user.password}")
private String soapGWPassword;
public Customer () {
// All parameters are null:
login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
}
}
但它们在 application.properties 文件中。
为什么在这种情况下我不能使用@Value?
最佳答案
在对象完全实例化之前,Spring 不会注入(inject)预属性的值(Spring 要做的第一件事就是调用您的构造函数,因为它是创建新对象的默认方式)。您应该在 @PostConstruct 方法中调用 login() 以便 Spring 在初始化对象后自动调用它:
@Service
public class Customer {
/** The soap GW endpoint. */
@Value("${soapGWEndpoint}")
private String soapGWEndpoint;
/** The soap GW app name. */
@Value("${soapGWApplName}")
private String soapGWAppName;
/** The soap GW user. */
@Value("${generic.user}")
private String soapGWUser;
/** The soap GW password. */
@Value("${generic.user.password}")
private String soapGWPassword;
public Customer () {
}
@PostConstruct
public void init() {
login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
}
}
关于java - 加载构造函数时值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54039484/
我是一名优秀的程序员,十分优秀!