1.添加攔截器java
package com.jy.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import yaycrawler.common.interceptor.SignatureSecurityInterceptor; @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { /** 添加攔截器
WebMvcConfigurerAdapter 顯示過時,則使用繼承至org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
*/ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MySignatureSecurityInterceptor()).addPathPatterns("/admin/**","/manager/**"); } }
二、建立監聽器web
package com.jy.listener; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.web.context.WebApplicationContext; /** * * 啓動worker監聽器 */ public class MyRegisterListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { WebApplicationContext context = (WebApplicationContext) contextRefreshedEvent.getApplicationContext(); WorkerContext.webApplicationContext = context; Userservice userservice = context.getBean(Userservice.class); //作其餘操做 } }
三、添加監聽器spring
package com.jy; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; import yaycrawler.worker.listener.WorkerRegisterListener; /** * 啓動時,向master註冊 */ public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//如上第二部建立的監聽器 application.listeners(new MyRegisterListener()); return application.sources(Application.class); } }
四、項目啓動時初始化操做(例如初始化項目根路徑)app
package com.jy.context; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.FileNotFoundException; @Component public class MyContextAware implements ApplicationContextAware { private Logger logger = LoggerFactory.getLogger(MyContextAware.class); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { //獲取跟目錄 File path = null; try { path = new File(ResourceUtils.getURL("classpath:").getPath()); if(!path.exists()) { path = new File(""); } //自行定義的類Global,ROOT爲static 變量;項目啓動時初始化項目路徑 Global.ROOT = path.getAbsolutePath()+File.separator; /* 在開發測試模式時,獲得的地址爲:{項目跟目錄}/target/classes/ 在打包成jar正式發佈時,獲得的地址爲:{發佈jar包目錄}/ */ } catch (FileNotFoundException e) { logger.error("FileNotFoundException",e); } logger.info("Global.ROOT {}",Global.ROOT); } }