本章目标
本章我们编写一个starter,目标如下:
1、通过@EnableSms 注解启用Starter
2、完成使用示例
Starter内容
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<name>demo-spring-boot-starter</name>
<groupId>com.v5ba</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
编写业务代码
@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);
}
}
创建@EnableSms注解,当开发者添加了此注解,无论MyConfiguration类是否被spring扫描到都会进行加载
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({MyConfiguration.class})
public @interface EnableSms {
}
使用Starter示例
1、创建springboot项目
2、引入starter jar包
<dependency>
<groupId>com.v5ba</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
3、在启动类添加@EnableSms注解,启用Starter
@EnableSms
@SpringBootApplication
public class StartApplication {
public static void main(String[] args) {
SpringApplication.run(StartApplication.class, args);
}
}
4、配置参数
com:
v5ba:
url: 192.168.1.1
user-name: v5ba
password: 123456
5、调用
@RestController
public class TestController {
@Autowired
private SmsUtil smsUtil;
@GetMapping("hello")
public String hello(){
smsUtil.send("18611111111", "消息内容");
return "ok";
}
}
本文链接:https://www.dzdvip.com/34674.html
版权声明:本文内容均来源于互联网。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 395045033@qq.com,一经查实,本站将立刻删除。