您能为每个回调提供至少一个使用示例吗?
查看每个接口的 javadoc,检查任何实现类的用途,并查找其实现的源代码。
典型的 bean 定义是
<bean id="someBean" class="com.example.beans.SomeBean">
<property name="someProperty" value="42" />
<property name="other" value="I will always love you." />
</bean>
像这样的类
public class SomeBean {
private String someProperty;
private String other;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public void setOther(String other) {
this.other = other;
}
}
但有时您的类需要根据属性集执行一些逻辑
public class SomeBean {
private String someProperty;
private String other;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public void setOther(String other) {
this.other = other;
}
public void init() {
Thread thread = new Thread(new Runnable() {
public void run() {
// for example
// send the two property values to some external service
}
});
thread.start();
}
}
该逻辑只能在设置属性后执行。在这种情况下,您可以让您的班级实现InitializingBean
接口(老派)
public class SomeBean implements InitializingBean {
private String someProperty;
private String other;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public void setOther(String other) {
this.other = other;
}
public void init() {
Thread thread = new Thread(new Runnable() {
public void run() {
// for example
// send the two property values to some external service
}
});
thread.start();
}
public void afterPropertiesSet() throws Exception {
init();
}
}
或者用注释来表示@PostConstruct
(新学校)
public class SomeBean implements InitializingBean {
private String someProperty;
private String other;
public void setSomeProperty(String someProperty) {
this.someProperty = someProperty;
}
public void setOther(String other) {
this.other = other;
}
@PostConstruct
public void init() {
Thread thread = new Thread(new Runnable() {
public void run() {
// for example
// send the two property values to some external service
}
});
thread.start();
}
}
这只是一个例子。这InitializingBean
接口经常与FactoryBean
界面。它有助于在生成对象之前初始化工厂。有关更多示例,请参阅这两个接口的 javadoc 并查找各个实现类的源代码。对另一个做同样的事情*Aware
接口。
As for AbstractRefreshableApplicationContext
,有时你需要refresh()
your ApplicationContext
。发生这种情况的原因可能是您想要重新加载 XML 配置,或者您的环境已更改,但您不想停止/重新启动应用程序。