您的位置:首页 > 编程语言 > Java开发

JAVA程序运行时就执行代码

2017-05-29 00:00 302 查看
我们在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("系统启动了(然后执行)");

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 启动 执行
相关文章推荐