SpringBoot_Day08自定义starter

一,如何编写自动配置

@Configuration //指定这个类是一个配置类 
@ConditionalOnXXX //在指定条件成立的情况下自动配置类生效 
@AutoConfigureAfter //指定自动配置类的顺序 
@Bean //给容器中添加组件 
@ConfigurationPropertie结合相关xxxProperties类来绑定相关的配置 
@EnableConfigurationProperties //让xxxProperties生效加入到容器中 自动配置类要能加载 将需要启动就加载的自动配置类,配置在META‐INF/spring.factories org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\

1.1 模式:

启动器只用来做依赖导入;

专门来写一个自动配置模块;

启动器依赖自动配置;别人只需要引入启动器(starter)

mybatis-spring-boot-starter;自定义启动器名-spring-boot-starter

二,例子

在这里插入图片描述

2.1 中 atguigu-spring-boot-starter引入

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

2.2atguigu-spring-boot-starter-autoconfigurer

1.HelloProperties

@ConfigurationProperties(prefix = "atguigu.hello")
public class HelloProperties {

    private String prefix;
    private String suffix;

2.HelloService

public class HelloService {

    HelloProperties helloProperties;

    public HelloProperties getHelloProperties() {
        return helloProperties;
    }

    public void setHelloProperties(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }

    public String sayHellAtguigu(String name){
        return helloProperties.getPrefix()+"-" +name + helloProperties.getSuffix();
    }
}

3.HelloServiceAutoCongfiguration

@Configuration
@ConditionalOnWebApplication //web应用才生效
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {

    @Autowired
    HelloProperties helloProperties;
    @Bean
    public HelloService helloService(){
        HelloService service = new HelloService();
        service.setHelloProperties(helloProperties);
        return service;
    }
}
  service.setHelloProperties(helloProperties);
    return service;
}

}



版权声明:本文为Njhbsj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Njhbsj/article/details/109010138