如何让springmvc在启动的时候执行特定的业务处理

java 的 web服务器启动时,经常会做一些特定的业务逻辑处理,比如数据库初始化,

初始化系统参数,读取配置文库等。

很多web服务的中间件,可以 通过这样的思路去实现。比如消息分发服务。

实现方法:

一、Web项目,非Spring

解决方法:实现【 ServletContextListener】 接口

(1)、把实现了ServletContextListener 的类配置到【 web.xml】 文件中

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  7. <display-name></display-name>
  8. <welcome-file-list>
  9. <welcome-file>index.jsp</welcome-file>
  10. </welcome-file-list>
  11. <listener>
  12. <listener-class>com.chinaso.init.StartInit</listener-class>
  13. </listener>
  14. <filter>
  15. <filter-name>struts2</filter-name>
  16. <filter-class>
  17. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  18. </filter-class>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>struts2</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24. </web-app>
    <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.chinaso.init.StartInit</listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

(2)、加入自己的实现逻辑

  1. public class StartInit implements ServletContextListener {
  2. static final Logger logger = LoggerFactory.getLogger(StartInit.class);
  3. // 系统初始化执行方法
  4. public void contextDestroyed(ServletContextEvent e) {
  5. logger.info("系统停止...");
  6. }
  7. public void contextInitialized(ServletContextEvent e) {
  8. logger.info("系统初始化开始...");
  9. // 获取项目根目录
  10. String root_path  = e.getServletContext().getRealPath("/");
  11. logger.info("application path : {}",root_path);
  12. // 初始化 ConfigFactorty
  13. ConfigFactory.init(root_path);
  14. // 初始化数据链接信息
  15. DBManager.init();
  16. // 初始化定时统计任务
  17. TaskManager.init();
  18. // 初始化用户信息查询位置
  19. UserInfo.init();
  20. logger.info("系统初始化结束...");
  21. }
  22. }
    public class StartInit implements ServletContextListener {
static final Logger logger = LoggerFactory.getLogger(StartInit.class);
// 系统初始化执行方法
public void contextDestroyed(ServletContextEvent e) {
logger.info("系统停止...");
} public void contextInitialized(ServletContextEvent e) {
logger.info("系统初始化开始..."); // 获取项目根目录
String root_path = e.getServletContext().getRealPath("/");
logger.info("application path : {}",root_path); // 初始化 ConfigFactorty
ConfigFactory.init(root_path);
// 初始化数据链接信息
DBManager.init();
// 初始化定时统计任务
TaskManager.init();
// 初始化用户信息查询位置
UserInfo.init(); logger.info("系统初始化结束...");
} }

二、Spring项目

Spring-MVC的应用中,要实现类似的功能,主要是通过实现下面这些接口(任选一,至少一个即可)

1、ApplicationContextAware接口

  1. package org.springframework.context;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.beans.factory.Aware;
  4. import org.springframework.context.ApplicationContext;
  5. public interface ApplicationContextAware extends Aware {
  6. void setApplicationContext(ApplicationContext var1) throws BeansException;
  7. }
package org.springframework.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.Aware;
import org.springframework.context.ApplicationContext; public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext var1) throws BeansException;
}

2、ServletContextAware 接口

  1. package org.springframework.web.context;
  2. import javax.servlet.ServletContext;
  3. import org.springframework.beans.factory.Aware;
  4. public interface ServletContextAware extends Aware {
  5. void setServletContext(ServletContext var1);
  6. }
package org.springframework.web.context;

import javax.servlet.ServletContext;
import org.springframework.beans.factory.Aware; public interface ServletContextAware extends Aware {
void setServletContext(ServletContext var1);
}

3、InitializingBean 接口

  1. package org.springframework.beans.factory;
  2. public interface InitializingBean {
  3. void afterPropertiesSet() throws Exception;
  4. }
package org.springframework.beans.factory;

public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}

4、ApplicationListener<ApplicationEvent> 接口

  1. package org.springframework.context;
  2. import java.util.EventListener;
  3. import org.springframework.context.ApplicationEvent;
  4. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  5. void onApplicationEvent(E var1);
  6. }
package org.springframework.context;

import java.util.EventListener;
import org.springframework.context.ApplicationEvent; public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}

java代码:

  1. package test.web.listener;
  2. import org.apache.logging.log4j.*;
  3. import org.springframework.beans.*;
  4. import org.springframework.beans.factory.InitializingBean;
  5. import org.springframework.context.*;
  6. import org.springframework.context.event.ContextRefreshedEvent;
  7. import org.springframework.stereotype.Component;
  8. import org.springframework.web.context.ServletContextAware;
  9. import javax.servlet.ServletContext;
  10. @Component
  11. public class StartupListener implements ApplicationContextAware, ServletContextAware,
  12. InitializingBean, ApplicationListener<ContextRefreshedEvent> {
  13. protected Logger logger = LogManager.getLogger();
  14. @Override
  15. public void setApplicationContext(ApplicationContext ctx) throws BeansException {
  16. logger.info("1 => StartupListener.setApplicationContext");
  17. }
  18. @Override
  19. public void setServletContext(ServletContext context) {
  20. logger.info("2 => StartupListener.setServletContext");
  21. }
  22. @Override
  23. public void afterPropertiesSet() throws Exception {
  24. logger.info("3 => StartupListener.afterPropertiesSet");
  25. }
  26. @Override
  27. public void onApplicationEvent(ContextRefreshedEvent evt) {
  28. logger.info("4.1 => MyApplicationListener.onApplicationEvent");
  29. if (evt.getApplicationContext().getParent() == null) {
  30. logger.info("4.2 => MyApplicationListener.onApplicationEvent");
  31. }
  32. }
  33. }
package test.web.listener;

import org.apache.logging.log4j.*;
import org.springframework.beans.*;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import javax.servlet.ServletContext; @Component
public class StartupListener implements ApplicationContextAware, ServletContextAware,
InitializingBean, ApplicationListener<ContextRefreshedEvent> { protected Logger logger = LogManager.getLogger(); @Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
logger.info("1 => StartupListener.setApplicationContext");
} @Override
public void setServletContext(ServletContext context) {
logger.info("2 => StartupListener.setServletContext");
} @Override
public void afterPropertiesSet() throws Exception {
logger.info("3 => StartupListener.afterPropertiesSet");
} @Override
public void onApplicationEvent(ContextRefreshedEvent evt) {
logger.info("4.1 => MyApplicationListener.onApplicationEvent");
if (evt.getApplicationContext().getParent() == null) {
logger.info("4.2 => MyApplicationListener.onApplicationEvent");
}
} }

运行时,输出的顺序如下:

1 => StartupListener.setApplicationContext
2 => StartupListener.setServletContext
3 => StartupListener.afterPropertiesSet
4.1 => MyApplicationListener.onApplicationEvent
4.2 => MyApplicationListener.onApplicationEvent
4.1 => MyApplicationListener.onApplicationEvent

注意:onApplicationEvent方法会触发多次,初始化这种事情,越早越好,建议在setApplicationContext方法中处理。

 

如何让springmvc在启动的时候执行特定的业务处理的更多相关文章

  1. springboot 学习之路 9 (项目启动后就执行特定方法)

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  2. spring mvc web应用启动时就执行特定处理(线程启动)

    package com.sdt.platform.index.controller; import java.net.URL; import java.util.List; import java.u ...

  3. Spring/SpringMVC在启动完成后执行方法

    在某些情况下,有可能你会有这种需求:在Spring/SpringMVC项目中,当Spring/SpringMVC启动完成后,你需要执行一个方法来完成某些事件(比如创建网站地图,比如从订阅Redis服务 ...

  4. Springboot - 在启动完成后执行特定方法

    1.实现方式 实现ApplicationRunner接口 实现CommandLineRunner接口 @Component @Slf4j public class AfterServiceStarte ...

  5. 如何让spring mvc web应用启动时就执行特定处理

    Asp.Net的应用中通过根目录下的Global.asax,在Application_Start方法中做一些初始化操作,比如:预先加载缓存项对网站热点数据进行预热,获取一些远程的配置信息等等. Spr ...

  6. 转载:如何让spring mvc web应用启动时就执行

    转载:如何让spring mvc web应用启动时就执行特定处理 http://www.cnblogs.com/yjmyzz/p/4747251.html# Spring-MVC的应用中 一.Appl ...

  7. springmvc拦截器入门及其执行顺序源码分析

    springmvc拦截器是偶尔会用到的一个功能,本案例来演示一个较简单的springmvc拦截器的使用,并通过源码来分析拦截器的执行顺序的控制.具体操作步骤为:1.maven项目引入spring依赖2 ...

  8. redhat的启动方式和执行次序

    rc.d的内容如下: init.d/ :各种服务器和程序的二进制文件存放目录. rcx.d/: 各个启动级别的执行程序连接目录.里头的东西都是指向init.d/的一些软连接.具体的后边叙述. 还有三个 ...

  9. java中服务器启动时,执行定时任务

    package com.ripsoft.util; import java.util.Calendar; import java.util.Timer; import javax.servlet.Se ...

随机推荐

  1. Jquery学习小计

    实时监听输入框值变化 首先创建Jquery.fn扩展 jQuery.fn.extend({ inputChange: function(callback){ if($.support.leadingW ...

  2. Maven和Gradle的比较

    Gradle和Maven都是项目构建工具,但是完全是两个产品,maven应该目前在java企业级开发中占的比重比较大,Gradle是后起之秀,Google的Android Stadio主推的就是Gra ...

  3. offset()和position()

    网上百度都有的说明是 offset():获取匹配元素在当前视口的相对偏移. position():获取匹配元素相对父元素的偏移. 如果单纯写这两句话,这个博客毫无意义 这里我写下他俩的使用情况,希望对 ...

  4. Java-Runoob-高级教程:Java Applet 基础

    ylbtech-Java-Runoob-高级教程:Java Applet 基础 1.返回顶部 1. Java Applet 基础 Applet 是一种 Java 程序.它一般运行在支持 Java 的 ...

  5. ESXI root密码忘记,重置root密码

    今天遇到了一个叫人比较头疼的问题,早在一个月前公司拉来一台服务器,闲着没事我给装成了Esxi的虚拟机系统了,时间过久忘了当时设定的密码为何?故而翻了许久的资料,终于找好的方向,准备重置系统密码.准备搞 ...

  6. 018:InnoDB 存储引擎、表空间

    目录 一.InnoDB 存储引擎 1. InnoDB的历史 2. InnoDB的特点 3. InnoDB存储引擎的文件 3.1 概述 3.2 InnoDB - 表空间 3.3 General表空间 3 ...

  7. node的socket.io类库概述

    socket.io是一个简单的小类库,该类库实现的功能类似于node中的net模块所实现的功能. 这些功能包括websocket通信,xhr轮询,jsonp轮询等. socket类库可以接受所有与服务 ...

  8. mysql where语句中 or 和 and连用注意点

    在mysql中,经常会遇到这样的情况,在写条件语句where时,可能会同时有多个条件的“或”或者“与”,但经常会达不到效果,经百度,本人发现一个where语句中同时出现条件的“与”或者“或的时候”,要 ...

  9. ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-前言与目录(转)

    开发工具:VS2015(2012以上)+SQL2008R2以上数据库 您可以有偿获取一份最新源码联系QQ:729994997 价格 666RMB 升级后界面效果如下: 日程管理   http://ww ...

  10. windows zabbix_agent 客户端安装部署

    1.下载客户端:zabbix_agentd.zip 2.在c盘创建文件夹zabbix,解压conf和bin目录 3.将conf下的zabbix_agentd.win.conf 修改为zabbix_ag ...