1. 程式人生 > >Servlet容器監聽器

Servlet容器監聽器

class string pre print ini common int mon sch

package com.biniu;

import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; /** * @Configuration, @EnableAutoConfiguration, @ComponentScan == @SpringBootApplication */ @SpringBootApplication @EnableScheduling @ServletComponentScan public class
BaseWebApplication { /** * 程序主方法 * @param args */ public static void main(String[] args) { // 調用Springboot的run方法,啟動Spring,自動配置servlet容器 SpringApplication.run(BaseWebApplication.class, args); } }
package com.biniu.Listener;

import com.biniu.properties.CommonProperties;
import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * Servlet容器監聽器 * Created by lay on 01/03/2018. */ @WebListener public class ServletCtxListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { System.out.println("servlet context 初始化開始"); ServletContext servletContext = servletContextEvent.getServletContext(); ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext); CommonProperties commonProperties = context.getBean(CommonProperties.class); // 設置圖片域名地址 String imageUrl = commonProperties.getImageUrl(); servletContext.setAttribute("imageUrl", imageUrl); System.out.println("servlet context 初始化完成"); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { System.out.println("servlet context 銷毀"); } }

Servlet容器監聽器