spring boot如何在所有bean初始化之前加载一个自定义类?

问题一

spring boot如何在所有bean初始化之前加载一个自定义类?

方案

首先创建一个class,继承ApplicationContextInitializer接口,并实现方法initialize,如下,

MyService

package com.eju.ess.controller;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyService implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext arg0) {
        log.info(">>>>>>>>>>>>>>");
    }

}

接着,在src/main/resources/目录中创建META-INF/spring.factories,并在其中添加内容,如下,
spring.factories

org.springframework.context.ApplicationContextInitializer=\com.eju.ess.controller.MyService

启动程序,如下打印日志,

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.2.RELEASE)

22:06:02.691 [main] INFO  com.eju.ess.controller.MyService - >>>>>>>>>>>>>>
22:06:02.714 [main] INFO  com.eju.ess.Startup - Starting Startup on DESKTOP-HP5AV5F with PID 7640 (D:\econf\econf-demo\target\classes started by zhaoq in D:\econf\econf-demo)
22:06:02.715 [main] INFO  com.eju.ess.Startup - No active profile set, falling back to default profiles: default
22:06:02.861 [main] INFO  org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6771beb3: startup date [Wed Apr 05 22:06:02 CST 2017]; root of context hierarchy
22:06:03.308 [background-preinit] INFO  org.hibernate.validator.internal.util.Version - HV000001: Hibernate Validator 5.3.4.Final
22:06:04.793 [main] INFO  org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer - Tomcat initialized with port(s): 8080 (http)
22:06:04.810 [main] INFO  org.apache.catalina.core.StandardService - Starting service Tomcat
22:06:04.812 [main] INFO  org.apache.catalina.core.StandardEngine - Starting Servlet Engine: Apac

参考文献

http://www.cnblogs.com/xinzhao/p/5551828.html

http://blog.csdn.net/chszs/article/details/50673075

==手机QQ扫描下方二维码,快速加入Java架构师交流群==

你可能感兴趣的:(spring,bean,Class)