在Spring中使用no args-constructor时,是否可以确保在初始化bean之前已经设置了一些属性?我想在创建bean之后使用InitializingBean
来验证设置。例如,我想做什么:
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!");
}
}
答案 0 :(得分:0)
要注入在运行时确定的内容,请考虑使用FactoryBean。它基本上是Factory模式,但本身支持Spring:
public class SomeWeirdMessageFactoryBean implements AbstractFactoryBean {
public Class<?> getObjectType() {
return String.class;
}
protected Object createInstance() throws Exception {
String message;
// magic:
[...]
return message;
}
}
magic
部分显然需要弄清楚要返回什么。然后你必须将它作为你的类的属性注入,而Spring将会发现它是一个工厂并为你做肮脏的工作。