Properties我没有在构造函数内部使用,而是看到@Value注解可以解决问题。
它可以在我拥有的另一个实现中工作,但在这里没有
控制器:
@Autowired
private Customer customer;
Run Code Online (Sandbox Code Playgroud)
我的课
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是它们位于application.properties文件中。
为什么在这种情况下我不能使用@Value?
另一种选择是像这样使用构造函数注入
@Service
public class Customer {
private String soapGWEndpoint;
private String soapGWAppName;
private String soapGWUser;
private String soapGWPassword;
@Autowired
public Customer(@Value("${soapGWEndpoint}") String soapGWEndpoint,
@Value("${soapGWApplName}") String soapGWAppName,
@Value("${generic.user}") String soapGWUser,
@Value("${generic.user.password}") String soapGWPassword) {
this.soapGWEndpoint = soapGWEndpoint;
this.soapGWAppName = soapGWAppName;
this.soapGWUser = soapGWUser;
this.soapGWPassword = soapGWPassword;
login(soapGWEndpoint, soapGWAppName, soapGWUser, soapGWPassword);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
在对象完全实例化之前,Spring不会注入预操作对象的值(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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
484 次 |
| 最近记录: |