有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring:启动和停止webapplication时更新DBtable条目

当应用程序启动和停止时,我必须更新一个表条目。 我有一个调用DAO方法的服务,但是当调用这个DAO方法时,自动连接的SessionFactory是空的

我使用了两种方法:

  1. @施工后,@PreDestroy
  2. applicationEvent()上的ApplicationListener

在这两种情况下,我在DAO类中将SessionFactory作为null。我在DAO类中使用Setter注入来注入SessionFactory

环境:JDBC数据源、Hibernate 3.4、Spring 3.1.2、Weblogic 10.3

如果你能给我指出正确的方向那就太好了

更新: 谢谢你的评论,我已经解决了。我们的应用程序是EAR,而我的DAOBean配置在另一个WAR的applicationContext中。xml。我将DAOBean配置移到了我的共享配置(appConfig.xml)中,它工作得很好。我使用了@PostConstruct和@PreDestroy


共 (2) 个答案

  1. # 1 楼答案

    可以使用SmartLifecycle接口,然后将其配置为bean:

    <bean class="com.my.package.MySmartlifecycle">
    

    以及您的实施:

    public class MySmartLifecycle implements SmartLifecycle{
        //autowire anything you need from context
        @Override
        public void start() {
            //do stuff on startup here
        }
    
        @Override
        public void stop() {
            //do stuff on shutdown here
        }
    
        @Override
        public boolean isRunning() {
            return false;
        }
    
        @Override
        public int getPhase() {
            return 0;
        }
    
        @Override
        public boolean isAutoStartup() {
            return true;
        }
    
        @Override
        public void stop(Runnable callback) {
    
        }
    
    }
    
  2. # 2 楼答案

    如果要在初始化上下文后执行方法,则必须使用ContextRefreshedEvent。在破坏上下文的情况下,您应该使用ContextStoppedEvent,但您还必须记住,不能保证会发布此事件

    @Component
    public class SpringStartedListener implements ApplicationListener<ContextRefreshedEvent> {
    
      @Override
      public void onApplicationEvent(ContextRefreshedEvent event) {
        // do something
      }
    }
    
    @Component
    public class SpringClosedListener implements ApplicationListener<ContextStoppedEvent> {
    
      @Override
      public void onApplicationEvent(ContextStoppedEvent event) {
        // do something
      }
    }
    

    如果您需要更多详细信息,请参阅http://www.tutorialspoint.com/spring/event_handling_in_spring.htm