学习spring-boot-starter自定义及应用

spring-boot-starter案例

通过下载以上附件,里面是2个idea项目,其中spring-boot-08-starter是自定义,spring-boot-08-starter-test是对该starter的应用,我们今天重点来分析spring-boot-08-starter自定义这个项目。

该项目分为2个模块atguigu-spring-boot-starter和atguigu-spring-boot-starter-autoconfigurer。众所周知,springboot的starter自定义规则是xxx-spring-boot-starter,atguigu-spring-boot-starter这个模块是一个简单的maven工程,只是描述xxx-spring-boot-starter的依赖关系,实现功能都是在atguigu-spring-boot-starter-autoconfigurer里面来做的。这样可以确保用户需要使用这个功能时,只需要引入xxx-spring-boot-starter这个依赖就可以,不需要去担心该功能依赖的其他模块。

atguigu-spring-boot-starter的pom.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.atguigu.starter</groupId>
    <artifactId>atguigu-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--引入启动器-->
    <dependencies>
        <!--引入自动配置模块-->
        <dependency>
            <groupId>com.atguigu.starter</groupId>
            <artifactId>atguigu-spring-boot-starter-autoconfigurer</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

接着我们来分析atguigu-spring-boot-starter-autoconfigurer是如何实现的

该模块有个主要实现类,该类是功能自动注入,如实现HelloService自动实例化并加入到spring容器中

@Configuration
@ConditionalOnWebApplication  //如果是web应用,该配置生效
@EnableConfigurationProperties(HelloProperties.class)//使该HelloProperties.class配置文件生效
public class HelloServiceAutoConfiguration {
    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService helloService=new HelloService();
        helloService.setHelloProperties(helloProperties);
        return helloService;
    }
}

那系统又是如何启动这个类,需要在根路径下META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.atguigu.starter.HelloServiceAutoConfiguration

通过springboot启动时,会自动加载该文件下的内容,至此HelloService 对象已经被实例化到spring容器中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值