springboot 自定义starter

序言

现在的项目都是以springboot为脚手架进行开发的主要原因是由于springboot有自动装载的功能,通俗的来讲,就是引入对应starter依赖就可以实现相应的功能,那我们如何实现自定义starter呢

应用场景

由于项目中都需要登录认证功能,我们可以把登录认证功能抽取,封装成starter,直接引入项目中,就可以实现登录认证功能。

公司公共依赖、响应体,异常等处理,都可以封装成starter创建自定义starter



1创建自定义starter

1.1配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>

    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.7.4
         
    
    com.gz
    hello-spring-boot-starter
    1.0-SNAPSHOT
    hello-spring-boot-starter
    hello-spring-boot-starter
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-configuration-processor
            true
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.projectlombok
            lombok
        
        
            org.springframework.boot
            spring-boot-autoconfigure
        
    

1.2创建service

public class HelloService {
    private String name;
    private String address;

    public HelloService(String name, String address) {
        this.name = name;
        this.address = address;
    }

    public String sayHello(){
        return "你好!我的名字叫 " + name + ",我来自 " + address;
    }
}

1.3创建配置类属性

@ConfigurationProperties(prefix = "hello")
@Data
public class HelloProperties {
    private String name;
    private String address;


}

1.4创建配置类

@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloServiceAutoConfiguration {
    private HelloProperties helloProperties;

    //通过构造方法注入配置属性对象HelloProperties
    public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
    //实例化HelloService并载入Spring IoC容器
    @Bean
    @ConditionalOnMissingBean
    public HelloService helloService(){
        return new HelloService(helloProperties.getName(),helloProperties.getAddress());
    }
}

1.5创建META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.gz.hellospringbootstarter.config.HelloServiceAutoConfiguration

2.创建测试项目

2.1创建controller

@RestController
@RequestMapping("/hello")
public class HelloController {
    //HelloService在我们自定义的starter中已经完成了自动配置,所以此处可以直接注入
    @Autowired
    private HelloService helloService;

    @GetMapping("/say")
    public String sayHello(){
        return helloService.sayHello();
    }
}

2.2引入pom.xml


        
            com.gz
            hello-spring-boot-starter
            1.0-SNAPSHOT
        

2.3 application.yml

hello
      name: guozhong
      address: qingdao

2.4访问



展开阅读全文

页面更新:2024-05-28

标签:脚手架   序言   通俗   容器   框架   实例   属性   功能   项目   公司

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top