2013-11-18 3 views
0

Кажется, что сеттер на моем бобах не работает.Весна JavaConfig setter не работает

Это моя весна конфигурации 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

Кстати, вам не нужно объявлять каждый фасоль с @Bean если ваш включен в @ComponentScan (»... ") – poussma

+0

с использованием сеттеров работает только для других ссылок на бобовые – poussma

ответ

0

Экземпляр, возвращаемый VCWebserviceClient, не является фактически используемым вашим приложением. Это весенний путь, чтобы узнать, какой класс импровизировать.

В любом случае, для вас вопрос, используйте @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... 

}

+0

Thx, который работает, но я хочу использовать сеттер – BigJ

+0

, почему? @Value поддерживает SPEL, который позволяет вам загружать значение из любого места (File, another bean, ...) – poussma

+0

Я хочу знать, как это работает. Но во-вторых, это упрощенный пример, мне нужно также вставлять бобы в другие бобы. – BigJ

Смежные вопросы