web项目启动执行方法

  近期在项目中需要将用户在web启动时就查询出来,当作缓存使用。

一、首先需要实现 ServletContextListener 接口

 1 public class UserCacheUtils implements ServletContextListener {
 2 
 3     /**
 4      * web服务器启动时执行
 5      */
 6     @Override
 7     public void contextInitialized(ServletContextEvent sce) {
 8       System.out.println("启动");
 9     }
10 
11     
12 
13     /**
14      * 消亡时执行
15      */
16     @Override
17     public void contextDestroyed(ServletContextEvent sce) {
18         System.out.println("关闭");
19     }
20 
21 }

  ServletContextListener 接口中有2个方法 contextInitialized 方法在web容器创建时执行,而 contextDestroyed 是在容器销毁时执行,所以我们可以将我们需要执行的代码加入到上述2个方法中。

二、Web.xml 配置监听

  我们要想执行上述代码就必须在Web.xml中配置监听去监听这个类。

1       <!-- 配置用户缓存监听路径 -->
2     <listener> 
3           <listener-class>com.dffk.audsys.common.util.UserCacheUtils</listener-class> 
4     </listener>

  这里要配置自己的类。

三、Bean 注入

  在这个类中,我们是不可以通过 @Autowired 获取到需要注入的 Bean ,这里我们需要使用 spring 进行对象注入。

 1 public class UserCacheUtils implements ServletContextListener {
 2     
 3     //获取spring注入的bean对象  
 4     private WebApplicationContext springContext;  
 5     
 6     @Autowired
 7     private SysUserMapper sysUserMapper;
 8 
 9     /**
10      * 存放所有人员信息,key为username
11      */
12     public static Map<String, SysUser> userMap;
13     /**
14      * web服务器启动时执行
15      */
16     @Override
17     public void contextInitialized(ServletContextEvent sce) {
18         springContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());  
19           if(springContext != null){  
20               sysUserMapper = (SysUserMapper)springContext.getBean("sysUserMapper");  
21           }else{  
22            System.out.println("获取应用程序上下文失败!");  
23            return;  
24           }  
25         System.out.println("启动");
26         getUsers();
27     }
28     
29     /**
30      * 缓存人员信息
31      */
32     public void getUsers () {
33         List<SysUser> users = sysUserMapper.findAllUsers();
34         users.stream().forEach((e) -> {
35             userMap.put(e.getUserName(), e);
36         });
37         userMap.keySet().stream().forEach(System.out :: println);
38     }
39     
40 
41     /**
42      * 消亡时执行
43      */
44     @Override
45     public void contextDestroyed(ServletContextEvent sce) {
46         System.out.println("关闭");
47     }
48 
49 }

  以上在 contextInitialized 方法中首先去初始化 需要注入的 bean,然后再去执行自己的方法。我的方法主要是为了将人员信息缓存下来。

猜你喜欢

转载自www.cnblogs.com/wuyx/p/9158986.html