springboot之starter

创建starter模块

创建的starter模块是一个空的jar包,里面只是做依赖管理,使用者只需将starter引入即可使用。

创建一个starter模块,命名为monkey1024-spring-boot-starter

在starter模块中加入autoconfigure模块的依赖

    <!--autoconfigure自动配置模块-->
    <dependency>
        <groupId>com.monkey1024</groupId>
        <artifactId>monkey1024-spring-boot-starter-autoconfigurer</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>

创建autoconfigure模块

创建一个autoconfigure模块,命名为monkey1024-spring-boot-autoconfigure

添加下面依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <!--为properties类生成相应的json文件-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

创建UserProperties类

@ConfigurationProperties(prefix = "monkey1024.user")
public class UserProperties {
    private String name;

    private String password;

    //get和set略
}

创建UserService类

public class UserService {

    private UserProperties userProperties;

    public UserService(UserProperties userProperties) {
        this.userProperties = userProperties;
    }

    public UserService() {}
    public boolean validate() {
        if ("admin".equals(userProperties.getName()) && "123".equals(userProperties.getPassword())) {
            return true;
        }

        return false;
    }

}

创建UserAutoConfiguration类

@Configuration
@ConditionalOnWebApplication//在web应用下启用
@EnableConfigurationProperties(UserProperties.class)//开启配置类
public class UserAutoConfiguration {

    @Autowired
    private UserProperties userProperties;

    @Bean
    @ConditionalOnMissingBean(UserService.class)//当容器中不存在该对象的时候创建
    public UserService addUserService() {
        return new UserService(userProperties);
    }
}

创建spring.factories文件

根据之前源码分析,我们需要在resources下创建META-INF文件夹,在该文件夹下创建spring.factories文件,里面内容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.monkey1024.UserAutoConfiguration

创建测试模块

创建测试web模块将上面的starter依赖导入。在配置文件中添加下面内容:

monkey1024.user.name=admin
monkey1024.user.password=123

创建controller

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/validate")
    public String validate() {
        boolean validate = userService.validate();

        return validate + "";
    }
}

在浏览器中发出请求即可看到返回true;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值