在Spring中使用no參數構造函數時,是否可以確保在初始化bean之前設置了一些屬性?我想在創建bean之後使用InitializingBean
來驗證設置。例如,我想要做什麼:Spring在使用無參數構造函數時確保已設置Bean屬性
public class HelloWorld implements InitializingBean{
private String message;
public HelloWorld()
{
//Only no-args constructor must be used
//How do we make sure 'message' was ever set before the Bean is used?
}
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
public void afterPropertiesSet(){
//Validate object, requires message to be set!
}
}
public class MainApp {
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
//Bean is instantiated
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
//Bean is initialized and thus afterPropertiesSet() is called here. It will fail because it requires 'message' to be set.
//Right after the bean is instantiated we set the 'message', but it's already to late. afterPropertiesSet() was already called.
obj.setMessage("Hello World!");
}
}
我不明白。你有'afterPropertiesSet',只是拋出一個異常或其他指標,它沒有被正確初始化。 –
可以將消息注入到該類中,因爲如果沒有注入它的依賴項(至少默認情況下),則無法創建該bean。基本上,容器將爲您完成整件事。 – mszymborski
@SotiriosDelimanolis那麼你會如何建議在給定的MainApp示例中創建Bean?在創建bean之前,我無法使用context.getBean調用obj.setMessage,該bean在創建bean的過程中執行afterPropertiesSet()。例外情況總是會發生。在給出的例子中,我沒有看到如何正確初始化bean。 – masi