web项目启动的时执行方法,实现有好多种,可以分为2大类:
1.使用web自带的:
(1)使用servlet,但是他不能使用spring 的bean 还需要手动获取,比较麻烦.
(2)创建一个类实现ServletContextListener 接口,实现里面的contextInitialized和contextDestroyed方法
package com.test. listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//创建的类名根据需要定义,但一定要实现ServletContextListener接口
public class WebContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
//这里可以放你要执行的代码或方法
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}
其中contextInitialized方法是项目在启动初始化的时候就会执行的方法,contextDestroyed是在消亡的时候执行的方法,这里我们需要把随项目启动时执行的代码放在contextInitialized方法中。
然后在web.xml中为这个监听器添加配置,
<listener>
<listener-class> com.test. listener.WebContextListener</listener-class>
</listener>
其中listenner-class配置的是上面定义的监听器类路径
这样就就可以了,部署好项目,启动就可以执行contextInitialized里面的代码了。
2.使用spring框架的话,实现比较多
(1)方法上加注解@PostConstruct
@Compant
public class InitDemo{
@PostConstruct
public void init(){
//项目启动就会执行这个方法
doSomething();
}
}
(2).xml配置init-method
我在spring的配置文件中添加上这条,这个配置只能在启动项目是执行一遍。
还有一点 要注意 这个方法不能是controller层的方法
<-- class是类的全名加包名 这是指定运行的方法在那个类里面 -->
<-- scope 值得范围 这里给的参数是 singleton -->
<-- inti-method 是指要执行的方法 -->
<bean id="InitDemo" class="com.xxx.InitDemo" scope="singleton" init-method="init">
</bean>
(3).实现InitializingBean接口,重写afterPropertiesSet方法
@Component
public class InitDemo implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
//doSomeThing
}
(4)实现ApplicationListener的listener类
@Service
public class StartupListener implements
ApplicationListener<ContextRefreshedEvent > {
public static String ShopNum ;
@Autowired
ShopService shopService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if ( event.getApplicationContext (). getParent() == null) {
// TODO 这里写下将要初始化的内容
Shop shopByShopNum = shopService
.getShopByShopNum ("e7-80-2e-e8-6c-a6" );
System.out .println ("----------------------------" );
} }}
(5)CommandLineRunner接口
使用CommandLineRunner接口类似于Main方法启动,可以接受一个字符串数组的命令行参数,来看一下实现
@Component
public class MyCommandLineRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception{
//假装有代码
}
}
(6)ApplicationRunner 接口
此种方式与实现CommandLineRunner接口的区别就是他的参数是ApplicationArguments
@Order(value = 1)
@Component
public class MyApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception{
//假装有代码
}
}
我们可以看到,此类相比较于第二种方式还增加一个@Order注解,这个注解其实第二种方式也是能加的。
它的作用就是控制类的加载顺序,这个顺序是从小到大的。比如说启动时先去加载Order的value等于1的类,然后去加载等于2的类。