我的bean上的setter似乎无法正常工作。
这是我的Spring java配置,SpringConfig.java:
@Configuration
@ComponentScan("com.xxxx.xxxxx")
public class SpringConfig {
@Bean(name="VCWebserviceClient")
public VCWebserviceClient VCWebserviceClient() {
VCWebserviceClient vCWebserviceClient = new VCWebserviceClient();
vCWebserviceClient.setSoapServerUrl("http://localhost:8080/webservice/soap/schedule");
return vCWebserviceClient;
}
VCWebserviceClient.java:
@Component
public class VCWebserviceClient implements VCRemoteInterface {
private String soapServerUrl;
public String getSoapServerUrl() {
return soapServerUrl;
}
public void setSoapServerUrl(String soapServerUrl) {
this.soapServerUrl = soapServerUrl;
}
// Implemented methods...
}
我的app.java:
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
VCWebserviceClient obj = (VCWebserviceClient) context.getBean("VCWebserviceClient");
System.out.println("String: "+obj.getSoapServerUrl()); // returns NULL
为什么obj.getSoapServerUrl()返回NULL?
This example显示了它应该如何运作。
答案 0 :(得分:0)
VCWebserviceClient
返回的实例不是您的应用程序实际使用的实例。这是Spring知道什么类实现的一种方式。
任何方式,对于您的问题,请使用@Value
(http://docs.spring.io/spring/docs/3.0.x/reference/expressions.html)
@Component
public class VCWebserviceClient implements VCRemoteInterface {
// spring resolves the property and inject the result
@Value("'http://localhost:8080/webservice/soap/schedule'")
private String soapServerUrl;
// spring automatically finds the implementation and injects it
@Autowired
private MyBusinessBean myBean;
public String getSoapServerUrl() {
return soapServerUrl;
}
public void setSoapServerUrl(String soapServerUrl) {
this.soapServerUrl = soapServerUrl;
}
// Implemented methods...
@Component
public class VCWebserviceClient implements VCRemoteInterface {
// spring resolves the property and inject the result
@Value("'http://localhost:8080/webservice/soap/schedule'")
private String soapServerUrl;
// spring automatically finds the implementation and injects it
@Autowired
private MyBusinessBean myBean;
public String getSoapServerUrl() {
return soapServerUrl;
}
public void setSoapServerUrl(String soapServerUrl) {
this.soapServerUrl = soapServerUrl;
}
// Implemented methods...