Web应用程序启动(春季3.0)

时间:2012-06-06 10:30:30

标签: web-applications spring-mvc startup

我希望在我的Web应用程序启动后(上下文加载)执行一个方法(或某些功能)。我使用spring 3.0作为框架。

我尝试使用我在类

中实现的ServletContextListener

我的听众课

package myapp.listner;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyContextListner implements ServletContextListener{

    public static long appStart=0L;
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("Context Destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        appStart=System.currentTimeMillis();
        System.out.println("Context Initialised");

    }

}

和web.xml的一部分是

<listner>
     <listner-class>myapp.listner.MyContextListner</listner-class>
    </listner>

    <servlet>
      <servlet-name>dispatcher</servlet-name>

      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/forms/*</url-pattern>
    </servlet-mapping>

但它不打印那条消息.....

请帮助我....

1 个答案:

答案 0 :(得分:3)

PostConstruct和PreDestroy注释,如下所示:

@Configuration
public class MyConfig{

    @PostConstruct
    public void contextInitialized(){
      System.out.println("Context Initialised");
    }

    @PreDestroy
    public void contextdestroyed(){
      System.out.println("Context Destroyed");
    }
}

您不必在配置bean中使用它,它可以是anywhere