理解SpringApplication

 

static WebApplicationType deduceFromClasspath() {
        if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) 
&& !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null)
 && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) {
            return REACTIVE;
        } else {
            String[] var0 = SERVLET_INDICATOR_CLASSES;
            int var1 = var0.length;

            for(int var2 = 0; var2 < var1; ++var2) {
                String className = var0[var2];
                if (!ClassUtils.isPresent(className, (ClassLoader)null)) {
                    return NONE;
                }
            }

            return SERVLET;
        }
    }
private static final String[] SERVLET_INDICATOR_CLASSES = new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};

DispatherHandler 是 webflux  里边一个重要的类,DispatcherServlet 是 web MVC 里面重要的类。当两者同时存在时,webflux 是不会起作用的

当第一个条件不满足时,就遍历  SERVLET_INDICATOR_CLASSES 这个数组, 若实现类 不是 Servlet 或者 ConfigurableWebApplicationContext , 就返回none.

否则返回  servlet.

我们可以设置应用类型

我们可以自定义一个初始化类, 实现ApplicationContextInitializer接口。 在resource 创建 META-INF/spring.factories文件。仿照上面的形式,把自定义的类放上即可。

 

自定义监听 容器刷新事件

编写spring.factories

即可完成监听。

工厂加载机制 : 去Spring.factories 文件中找实现类。

我们若 自定义 运行监听器, 把自定义运行监听器,配置在 resource/META-INF/spring.factories 文件中即可。

Spring Framework 事件监听器 使用

public class SpringApplicationEventBootstrap {

    public static void main(String[] args) {

        //创建上下文
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

        //注册应用事件监听器
        context.addApplicationListener(event -> System.out.println("监听到事件"+event));
        //启动上下文
        context.refresh();

        //发事件
        context.publishEvent("Hello,World");

        context.publishEvent(new ApplicationEvent("SpringEvent") {

        });

        //关闭上下文
        context.close();
    }

运行结果:

自定义SpringBoot 运行监听器

SpringBoot 运行监听器 是工厂机制加载的,所以我们按照给定的规则进行配置即可。把 自定义监听器 配置到  spring.factories 里边

public class HelloWorldRunListener  implements SpringApplicationRunListener {

    public HelloWorldRunListener(SpringApplication application, String[] args){

    }

    public void starting() {
        System.out.println("HelloWorldRunListener  starting ........");
    }
    // 下边还可实现其他方法

}

配置:

自定义监听器 的构造器一定要按照上面方式写, 因为在创建 监听器实例时,是根据构造器 反射实例化的。

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值