本章我们编写一个自动配置starter,目标如下:
1、Starter 读取配置参数,将对外提供的实例交由 IOC容器管理
2、完成使用示例
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
4.0.0
demo-spring-boot-starter
com.v5ba
demo-spring-boot-starter
1.0-SNAPSHOT
jar
UTF-8
1.8
1.8
org.springframework.boot
spring-boot-starter
编写业务代码
@Data
@ConfigurationProperties(prefix = "com.v5ba")
public class SmsProperties {
private String url;
private String userName;
private String password;
}
public class SmsUtil {
private SmsProperties smsProperties;
public SmsUtil(SmsProperties smsProperties) {
this.smsProperties = smsProperties;
}
public boolean send(String phone, String content) {
System.out.println("短信发送成功:"
+smsProperties.getUrl()+"--"
+smsProperties.getUserName()+"--"
+smsProperties.getPassword());
return true;
}
}将SmsUtil类交给Spring IOC管理,并提供给第三方使用
@Configuration
public class MyConfiguration {
@Bean
public SmsProperties smsProperties(){
return new SmsProperties();
}
@Bean
public SmsUtil smsUtil(SmsProperties smsProperties){
return new SmsUtil(smsProperties);
}
}上边的代码我们很熟悉也经常用到就不介绍了,重点是spring.factories 的配置,无论MyConfiguration类是否被spring扫描到都会进行加载
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.v5ba.common.MyConfiguration1、引入starter jar包
2、配置参数
com:
v5ba:
url: 192.168.1.1
user-name: v5ba
password: 123456
3、调用
@RestController
public class TestController {
@Autowired
private SmsUtil smsUtil;
@GetMapping("hello")
public String hello(){
smsUtil.send("18611111111", "消息内容");
return "ok";
}
} | 留言与评论(共有 0 条评论) “” |