springboot自定义starter

案例1:自定义starter中配置用户信息、接口访问。使用starter时在yml文件配置用户信息

1,创建自定义starter
1.1,创建starter工程xxx-spring-boot-starter并配置pom.xml文件

<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

/*
 *读取配置文件转换为bean
 * */
@Data
@ConfigurationProperties(prefix = "xxx")
public class XXXProperties {
    private String name;
    private String address;
}

1.3,创建自动配置类XXXServiceAutoConfiguration

@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

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration

1.5,创建UserInfo

@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类

@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依赖

//省略
<dependencies>
    <!--导入自定义starter-->
    <dependency>
        <groupId>cn.tianqing</groupId>
        <artifactId>tianqing-spring-boot-starter</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
</dependencies>

2.2,修改application.yml文件

xxx:
  name: xiaoming
  address: beijing

2.3,调用自定义starter中服务

@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依赖

<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注解

@Target(ElementType.METHOD)//仅在方法上使用
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {
    /**
     * 方法描述
     */
    String desc() default "";
}

1.3,自定义日志拦截器MyLogInterceptor

/**
 * 日志拦截器
 */
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组件

/**
 * 配置类,用于自动配置拦截器、参数解析器等web组件
 */
@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer{
    //注册自定义日志拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyLogInterceptor());
    }
}

1.5,在spring.factories中追加MyLogAutoConfiguration配置

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.meteorological.config.XXXAutoConfiguration,\
cn.meteorological.config.MyLogAutoConfiguration

2,使用自定义starter
2.1,Controller方法上加入@MyLog注解

@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,查看控制台输出:

请求uri:/hello/say
请求方法名:cn.meteorological.controller.HelloController.sayHello
方法描述:sayHello方法
方法执行时间:36ms
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值