0

我的 bean 上的设置器似乎不起作用。

这是我的 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?

这个例子展示了它应该如何工作。

4

1 回答 1

0

返回的实例VCWebserviceClient不是您的应用程序实际使用的实例。这是 Spring 知道要实例化哪个类的一种方式。

无论如何,对于您的问题,请使用@Valuehttp://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...

}

于 2013-11-18T10:51:32.753 回答