JAVA程序运行时就执行代码

我们在JAVA开发的过程中,往往需要在程序一启动时就执行一些操作,例如载入基本数据或初始化系统什么的。
这是用了监听器(Listener)实现的,参考书籍《轻量级Java EE》企业应用实战(第4版) 李刚编著
 package com.cn.bwq.init;

 

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import javax.servlet.annotation.WebListener;

@WebListener

public class Startup implements ServletContextListener{

 

//@Override

public void contextDestroyed(ServletContextEvent arg0) {

// TODO Auto-generated method stub

System.out.println("程序销毁了");

}

 

//@Override

public void contextInitialized(ServletContextEvent arg0) {

// TODO Auto-generated method stub

System.out.println("程序启动了(首先执行)");

}

 

}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

以下代码在程序启动时同样也会被执行,不过是先执行上面的,再执行下面的
package com.cn.bwq.init;

 

import org.springframework.context.ApplicationEvent;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextRefreshedEvent;

import org.springframework.stereotype.Service;

 

@Service

public class StartupBySpringMvc implements ApplicationListener<ContextRefreshedEvent> {

 

@Override

public void onApplicationEvent(ContextRefreshedEvent evt) {

// TODO Auto-generated method stub

if(evt.getApplicationContext().getParent() != null){

System.out.println("系统启动了(然后执行)");

}

}

 

}

转载于:https://my.oschina.net/u/3439048/blog/910991

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值