SpringBoot自定义starter

1.创建一个maven项目,命名为xxx-spring-boot-starter
<parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.0.4.RELEASE</version>
 </parent>
<dependencies>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
     </dependency>
 </dependencies>
2.编写配置类
@Configuration
@EnableConfigurationProperties(TestUserProperties.class)
@ConditionalOnClass({User.class})
public class TestAutoConfiguration {

    @Resource
    private TestUserProperties testUserProperties;

    @Bean
    public User getUser(){
        User user = new User();
        user.setName(testUserProperties.getName());
        user.setAge(testUserProperties.getAge());
        user.setAddress(testUserProperties.getAddress());
        return user;
    }

}
@Configuration
@ConfigurationProperties(prefix = "test.user")
public class TestUserProperties {

    private String name;

    private Integer age;

    private String address;
    
	// getter/setter
}
public class User {

    private String name;

    private Integer age;

    private String address;
    
	// getter/setter
}
3.进行自动配置

resources -> META_INF -> spring.factories # SpringBoot 2.7以前写法,2.7版本废除,3版本后终止使用
resources -> META_INF -> spring -> org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件

2.7以下版本
在这里插入图片描述

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.linging.config.TestAutoConfiguration

3.0以上版本:
在这里插入图片描述

com.linging.config.TestAutoConfiguration

2.7~3.0之间,两种方式共存。

4.打jar包,使用maven进行install
5.新建一个springboot项目,引入依赖:
<dependency>
     <groupId>com.linging</groupId>
     <artifactId>linging-spring-boot-starter</artifactId>
     <version>1.0-SNAPSHOT</version>
 </dependency>

同时yaml文件进行配置:

test:
  user:
    name: 张三
    age: 18
    address: 深圳

编写controller进行注入:

@RequestMapping("/test")
@RestController
public class TestController {

    @Resource
    private User user;
    
    @GetMapping("/starter")
    public String starter(){
        return JSON.toJSONString(user);
    }
}

访问结果:http://localhost:8081/test/starter
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值