手写一个stater_手写一个starter

命名规范

自定义 starter,工程命名格式为{xxx}-spring-boot-starter。

官方starter,工程命名格式为spring-boot-starter-{xxx}。

创建流程

定义核心业务类,这是该 Starter 存在的意义。

定义自动配置类,其完成对核心业务类的实例化。

若核心业务类中需要从配置文件获取配置数据,还需要定义一个用于封装配置文件中相关属性的类。

定义 META-INF/spring.factories 配置文件,用于对自动配置类进行注册。

案例演示

starter功能介绍:

①功能很简单,实现输出“hello world”;

②可以接受一个配置参数,如果参数值为“wonderful”,则应该输出“hello wonderful world”;

③同时接受另一个参数,用于控制前一个参数是否生效,值为“true”则生效,默认生效,否则不生效。

定义starter

使用idea创建sping boot maven项目,选择如下依赖

pom.xml

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-configuration-processor

true

org.projectlombok

lombok

true

编写业务类WorldService

/**

* 核心业务实现类

*/

@AllArgsConstructor

public class WorldService {

private String adjective;

public String hello() {

return "hello " + adjective + " world !";

}

}

添加属性封装类AdjectiveProperties

/**

* 属性封装类

* >>要读取配置文件中的"world.service.adjective"

*

*/

@ConfigurationProperties("world.service") //属性前缀

@Data

public class AdjectiveProperties {

private String adjective;

}

配置类WorldServiceAutoConfiguration

@Configuration

@ConditionalOnClass(WorldService.class)

@EnableConfigurationProperties(AdjectiveProperties.class)

public class WorldServiceAutoConfiguration {

@Autowired

private AdjectiveProperties properties;

@Bean

@ConditionalOnProperty(name = "world.service.enable", havingValue = "true", matchIfMissing = true)

public WorldService worldService() {

return new WorldService(properties.getAdjective());

}

@Bean

@ConditionalOnMissingBean

public WorldService worldService2() {

return new WorldService("");

}

}

配置类注册spring.factories

在resources目录下新建META-INF/spring.factories文件,添加如下内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.config.WorldServiceAutoConfiguration

最后,maven打包,一个starter就算定义完成了。接下来验证一下。

验证starter

使用idea创建helloworldtest项目,导入spring-boot-starter-web依赖,同时添加我们刚刚定义好的world-spring-boot-starter。

pom.xml

com.example

world-spring-boot-starter

0.0.1-SNAPSHOT

org.springframework.boot

spring-boot-starter-web

WorldController.java

@RestController

public class WorldController {

@Autowired

private WorldService worldService;

@RequestMapping("/world")

public String hello() {

return worldService.hello();

}

}

application.properties配置如下验证

world.service.enable = true

world.service.adjective= wonderful

application.properties配置如下验证

world.service.enable = false

world.service.adjective= wonderful

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值