在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