☞ Round 1 应用挂载监听
实现ApplicationListener接口
123456789public class CheApplicationEnvironmentPreparedEventListener implementsApplicationListener<ApplicationEnvironmentPreparedEvent>{@Overridepublic void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {// 核心功能写在这里哟}}main方法中,application.addListeners挂载
12345public static void main(String[] args) {SpringApplication application = new SpringApplication(AuthCenterApplication.class);application.addListeners(new CheApplicationEnvironmentPreparedEventListener());application.run(args);}分析
- 监听实现可以抽取到公共服务,但是每个微服务主函数都需要写一遍监听挂载
- 硬编码,例如:无法通过yml配置文件动态关闭开启挂载的核心功能
☞ Round 2 spring.factories挂载监听
实现ApplicationListener接口
- 通过event获取Environment可取得bootstap.yml配置文件内容,实现开关功能
- 若遇到监听重复加载2次情况,可通过event.getSpringApplication().getWebApplicationType().name())加以区分1234567891011121314public class CheApplicationEnvironmentPreparedEventListener implementsApplicationListener<ApplicationEnvironmentPreparedEvent>{@Overridepublic void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {// spring.application.log 开启日志// 监听注入2次,name分别为NONE、SERVLETif("true".equals(event.getEnvironment().getProperty("che.xx")) &&"SERVLET".equals(event.getSpringApplication().getWebApplicationType().name())) {// 核心功能写在这里哟}}}
src/main/resources/spring.factories文件添加监听
|
|
- 分析
- spring.factories可抽取至公共服务
- 默认不启用,仅能通过bootstrap.yml自定义开启,无法通过application.yml设置
☞ Round 3 自定义@Enable 注解
EnableCheLog注解类
1234567@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)@Documented@Import({LogImportSelector.class})public @interface EnableCheLog {}LogImportSelector类
123456789101112131415161718public class LogImportSelector implements ImportSelector, EnvironmentAware {private Environment environment;@Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) {// environment获取yml配置作为开关if("true".equals(environment.getProperty("che.xx"))) {// 核心功能写在这里哟}return new String[]{};}@Overridepublic void setEnvironment(Environment environment) {this.environment = environment;}}启动类
123456@EnableCheLogpublic class AuthCenterApplication {public static void main(String[] args) {SpringApplication.run(AuthCenterApplication.class, args);}}分析
- EnableCheLog、LogImportSelector放在公共服务
- 支持所有yml配置文件设置开关,当然也可以利用yml配置进行核心业务开发