如何在Spring中将shutdownHook配置为Runtime

时间:2015-11-11 13:51:17

标签: spring

我正在研究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)上有例外

2 个答案:

答案 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));