案例1:自定义starter中配置用户信息、接口访问。使用starter时在yml文件配置用户信息
1,创建自定义starter
1.1,创建starter工程xxx-spring-boot-starter并配置pom.xml文件
java
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>cn.xxx</groupId>
<artifactId>xxx-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
</dependencies>
</project>
1.2,创建配置属性类XXXProperties
java
/*
*读取配置文件转换为bean
* */
@Data
@ConfigurationProperties(prefix = "xxx")
public class XXXProperties {
private String name;
private String address;
}
1.3,创建自动配置类XXXServiceAutoConfiguration
java
@Configuration
//启用配置属性类
@EnableConfigurationProperties(TQProperties.class)
public class TianQingAutoConfiguration {
private TQProperties tqProperties;
//通过构造方法注入配置属性对象HelloProperties
public TianQingAutoConfiguration(TQProperties tqProperties) {
this.tqProperties = tqProperties;
}
//实例化UserInfo并载入Spring IoC容器
@Bean
@ConditionalOnMissingBean
public UserInfo userInfo(){
return new UserInfo (tqProperties.getName(),tqProperties.getAddress());
}
}
1.4,在resources目录下创建META-INF/spring.factories
java
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration
1.5,创建UserInfo
java
@Data
public class UserInfo {
private String name;
private String address;
public UserInfo (String name, String address) {
this.name = name;
this.address = address;
}
}
1.6,创建server类
java
@Service
public class DMService {
@Autowired
private UserInfo userInfo;
public String getInfo(){
return userInfo.getName()+" address: "+userInfo.getAddress();
}
}
2,使用starter
2.1,创建maven工程并配置pom.xml文件,加入自定义starter依赖
java
//省略
<dependencies>
<!--导入自定义starter-->
<dependency>
<groupId>cn.tianqing</groupId>
<artifactId>tianqing-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
2.2,修改application.yml文件
java
xxx:
name: xiaoming
address: beijing
2.3,调用自定义starter中服务
java
@Component
public class CustomStarterTest {
//注入自定义starter中的server类
@Autowired
DMService dmService;
@PostConstruct
public void task1() {
System.out.println(dmService.getInfo());
}
}
案例2:自定义拦截器记录服务执行时间
1.1,自定义starter的pom.xml文件中添加web依赖
java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
1.2,自定义MyLog注解
java
@Target(ElementType.METHOD)//仅在方法上使用
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
/**
* 方法描述
*/
String desc() default "";
}
1.3,自定义日志拦截器MyLogInterceptor
java
/**
* 日志拦截器
*/
public class MyLogInterceptor extends HandlerInterceptorAdapter {
private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
//获得被拦截的方法对象
Method method = handlerMethod.getMethod();
//获得方法上的注解
MyLog myLog = method.getAnnotation(MyLog.class);
if(myLog != null){
//方法上加了MyLog注解,需要进行日志记录
long startTime = System.currentTimeMillis();
startTimeThreadLocal.set(startTime);
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
HandlerMethod handlerMethod = (HandlerMethod)handler;
//获得被拦截的方法对象
Method method = handlerMethod.getMethod();
//获得方法上的注解
MyLog myLog = method.getAnnotation(MyLog.class);
if(myLog != null){
//方法上加了MyLog注解,需要进行日志记录
long endTime = System.currentTimeMillis();
//ThreadLocal中获取开始时间
Long startTime = startTimeThreadLocal.get();
long optTime = endTime - startTime;
System.out.println("方法执行时间:" + optTime + "ms");
String requestUri = request.getRequestURI();
//类名+方法名
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
String methodDesc = myLog.desc();
System.out.println("请求uri:" + requestUri);
System.out.println("请求方法名:" + methodName);
System.out.println("方法描述:" + methodDesc);
}
}
}
1.4,创建自动配置类MyLogAutoConfiguration,用于自动配置拦截器、参数解析器等web组件
java
/**
* 配置类,用于自动配置拦截器、参数解析器等web组件
*/
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer{
//注册自定义日志拦截器
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyLogInterceptor());
}
}
1.5,在spring.factories中追加MyLogAutoConfiguration配置
java
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration,\
cn.meteorological.config.MyLogAutoConfiguration
2,使用自定义starter
2.1,Controller方法上加入@MyLog注解
java
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private HelloService helloService;
//日志记录注解
@MyLog(desc = "sayHello方法")
@GetMapping("/say")
public String sayHello(){
return helloService.sayHello();
}
}
2.2,访问地址:http://localhost:8080/hello/say,查看控制台输出:
java
请求uri:/hello/say
请求方法名:cn.meteorological.controller.HelloController.sayHello
方法描述:sayHello方法
方法执行时间:36ms