我正在研究bean生命周期,我正在使用回调接口:'InitializingBean'和'DisposableBean'来实现生命周期方法,除了在我的主类中,我试图将shutdownHook添加到 运行时对象,以便我不需要调用
((ConfigurableListableBeanFactory) factory).destroySingletons();
手动。这就是我创建一个ShutdownHook类
的地方 public class ShutDownHook implements Runnable, BeanFactoryAware {
private BeanFactory factory;
@Override
public void setBeanFactory(BeanFactory factory) throws BeansException {
System.out.println("performing aware injection");
this.factory = factory;
}
@Override
public void run() {
((ConfigurableListableBeanFactory) factory).destroySingletons(); -----> X
}
}
我的主要课程就像
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("com/bli/common/application-context.xml"));
Math math = factory.getBean("math", Math.class);
ShutDownHook shutDownHook = factory.getBean("shutdownhook", ShutDownHook.class);
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread(new ShutDownHook()));
}
以下是我想要执行初始化和销毁的Bean
public class Math implements InitializingBean, DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("destroyed....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("performed initialization ...");
}
我在spring bean configurtion文件中配置了所需的bean
<bean id="math" class="com.bli.beans.Math">
<constructor-arg value="10"></constructor-arg>
<property name="y" value="20"></property>
</bean>
<bean id="shutdownhook" class="com.bli.beans.ShutDownHook"></bean>
执行此程序后,我得到RuntimeException为
performed initialization ...
performing aware injection
Exception in thread "Thread-0" java.lang.NullPointerException
at com.bli.beans.ShutDownHook.run(ShutDownHook.java:20)
at java.lang.Thread.run(Thread.java:745)
当控制器进入shutdownHook类的run方法时,对工厂的引用正在迷失..我不知道为什么 我在代码
中标记的行(x)上有例外答案 0 :(得分:2)
您可以在main方法中使用单个调用替换所有上述逻辑:
context.registerShutdownHook();
请注意,您需要使用从AbstractApplicationContext
而非BeanFactory
派生的实例,但这很容易实现(即创建GenericXmlApplicationContext
的实例)。
有关方法
,请参阅JavaDoc答案 1 :(得分:0)
编辑您的主要方法,如下所示,您的NullPointerException问题将得到解决:)
ShutDownHook shutDownHook = factory.getBean("shutdownhook", ShutDownHook.class);
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread(shutDownHook));