• SpringBoot-自定义Starter


    目录

    一、starter启动原理

             二、自定义 Starter


    一、starter启动原理

    • starter-pom引入 autoconfigurer
    • autoconfigure包中配置使用 META-INF/spring.factoriesEnableAutoConfiguration 的值,使得项目启动加载指定的自动配置类

    二、自定义 Starter

            首先在一个工程里创建两个项目,一个普通maven项目,另一个使用spring-initializer。

             修改starter的配置文件,加入下面内容:

    1. <dependency>
    2. <groupId>com.atguigugroupId>
    3. <artifactId>atguigu-hello-spring-boot-starter-autoconfigureartifactId>
    4. <version>0.0.1-SNAPSHOTversion>
    5. dependency>

            在autoconfigure包下创建spring.factories文件

    1. # Auto Configure
    2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    3. com.atguigu.hello.auto.HelloServiceAutoConfiguration

            创建相应的包、类

     

    1. @Configuration
    2. @EnableConfigurationProperties(HelloProperties.class) //默认HelloProperties放在容器中
    3. public class HelloServiceAutoConfiguration{
    4. @ConditionalOnMissingBean(HelloService.class)
    5. @Bean
    6. public HelloService helloService(){
    7. HelloService helloService = new HelloService();
    8. return helloService;
    9. }
    10. }
    1. /**
    2. * 默认不要放在容器中
    3. */
    4. public class HelloService {
    5. @Autowired
    6. HelloProperties helloProperties;
    7. public String sayHello(String userName){
    8. return helloProperties.getPrefix() + ":"+userName+"》"+helloProperties.getSuffix();
    9. }
    10. }
    1. @ConfigurationProperties("atguigu.hello")
    2. public class HelloProperties {
    3. private String prefix;
    4. private String suffix;
    5. public String getPrefix() {
    6. return prefix;
    7. }
    8. public void setPrefix(String prefix) {
    9. this.prefix = prefix;
    10. }
    11. public String getSuffix() {
    12. return suffix;
    13. }
    14. public void setSuffix(String suffix) {
    15. this.suffix = suffix;
    16. }
    17. }

            分别cleaninstall autoconfigure包和starter包,存到本地maven仓库中

             去新的工程中引用自定义starter包

    1. <dependency>
    2. <groupId>com.atguigugroupId>
    3. <artifactId>atguigu-hello-spring-boot-starterartifactId>
    4. <version>1.0-SNAPSHOTversion>
    5. dependency>

           在application.yaml中配置参数

    1. atguigu:
    2. hello:
    3. prefix: hello
    4. suffix: you are beautiful

            测试

    1. @RestController
    2. public class helloController {
    3. @Autowired
    4. HelloService helloService;
    5. @GetMapping("/iKun")
    6. public String helloIKun(){
    7. return helloService.sayHello("cxk");
    8. }
    9. }
  • 相关阅读:
    Vue·修改启动端口
    AGI概念与实现
    合并多个.a库为一个.a库
    java常见面试题(未整理,后续可能一直更新)
    ASUS (k013) ME176CX不进入系统恢复出厂设置的方法
    全球第六大IT服务提供商富士通遭黑客攻击:多个系统被感染、客户敏感数据泄露
    Android开机动画
    Ubuntu下安装Teamviewer所遇certificates.crt CRLfile: none问题
    用于机器学习的 NumPy(ML)
    第四站:数组
  • 原文地址:https://blog.csdn.net/weixin_62427168/article/details/126181932