自定义 Spring Boot Starter 自动装配实战

最简单的自定义 Spring Boot Starter 实战

1.创建一个最简单的Maven工程

  • 只需要依赖 spring-context 即可
    在这里插入图片描述
  • 然后写添加 如下的代码
package com.learn.autoconfiguration.stater;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * describe:
 *
 * @author huyi
 * @date 2020/08/05
 */
@Configuration
public class HuyiConfiguration {

    @Bean
    public HuyiEduCore huyiEduCore(){
        return new HuyiEduCore();
    }
}

/**
 * describe:
 *
 * @author huyi
 * @date 2020/08/05
 */
public class HuyiEduCore {
    public void learn(){
        System.out.println("huyi 正在学习 Spring Boot 自动装配原理!");
    }
}
  • 然后就是META-INF目录下的 spring.facotries
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.learn.autoconfiguration.stater.HuyiConfiguration

2.创建一个Spring Boot 工程

在这里插入图片描述

  • 添加如下代码

import com.learn.autoconfiguration.stater.HuyiEduCore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootDemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ca = SpringApplication.run(SpringbootDemoApplication.class, args);
        HuyiEduCore bean = ca.getBean(HuyiEduCore.class);
        bean.learn();
    }

}

install 一下huyi-starter 工程,给spring-boot-demo工程依赖huyi-starter

启动运行

在这里插入图片描述

Spring Boot 自动装配原理

核心逻辑

  • 1.@SpringBootApplication 组合注解中 包含@EnableAutoConfiguration注解
    在这里插入图片描述

  • 2.@EnableAutoConfiguration 注解中 @Import({AutoConfigurationImportSelector.class})
    在这里插入图片描述

  • 3.AutoConfigurationImportSelector.class该类里面的逻辑是 加载 Classpath下
    MEAT-INF/spring.factories (spring.factories 文件里写了各个需要自动装配模块的 配置类全路径,该文件可以在很多包下都可能有)
    调试图片

  • 4.然后解析这些配置类,并且向容器中注入对应例如HuyiEduCore.class 等这些类,我们就可以直接拿来用了
    在这里插入图片描述

  • 前提要了解 @Configuration @Import 这些基本注解

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值