【springboot】自定义starter(学习笔记)

9 篇文章 0 订阅
5 篇文章 0 订阅
本文介绍了如何创建自定义的Spring Boot Starter,包括配置属性、自动配置类和条件化Bean的创建。此外,还展示了如何在Starter中添加拦截器以实现日志记录功能,通过@MyLog注解来标记需要拦截的方法,并在拦截器中记录方法的执行时间和描述。
摘要由CSDN通过智能技术生成

起步依赖

自动配置

条件依赖

Bean参数获取

Bean的发现

bean的加载

总结

自定义starter案例一:hello-spring-boot-starter

pom文件

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.7.2</version>
        <relativePath/>
    </parent>
    <groupId>com.malguy</groupId>
    <artifactId>hello-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <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>
    </dependencies>
</project>

配置属性类HelloProperties

import org.springframework.boot.context.properties.ConfigurationProperties; 
/**
* 配置属性类,封装配置文件里的信息
* 对应配置文件
*   hello:
*     name:
*     address:
*/
@ConfigurationProperties(prefix="hello") //参数的前缀;
public class HelloProperties {
    private String name;
    private String address;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
    public String getAddress() {
        return address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        return "HelloProperties{" +
            "name='" + name + '\'' +
            ", address='" + address + '\'' +
            '}';
    }
}

服务类(到时boot会自动创建)HelloService

public class HelloService {
    private String name;
    private String address;

    public HelloService(String name, String address) {
        this.name = name;
        this.address = address;
    }
    public String sayHello(){
        return "你好,my name is "+name+",我 coming from "+address;
    }
}

HelloServiceAutoConfiguration

/**
 * 自动配置类,自动配置hello对象
 */
@Configuration
@EnableConfigurationProperties(value=HelloProperties.class)
public class HelloServiceAutoConfiguration {
    private HelloProperties helloProperties;
    //通过构造方法注入配置对象
    public HelloServiceAutoConfiguration(HelloProperties helloProperties) {
        this.helloProperties = helloProperties;
    }
    @Bean
    @ConditionalOnMissingBean //当没有这个bean的时候才创建
    public HelloService helloService(){
        return new HelloService(
                helloProperties.getName(),
                helloProperties.getAddress()
        );
    }
}

resources目录下创建META-INF/spring.factories , 可以加载自动配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.malguy.config.HelloServiceAutoConfiguration

这样就可以install再使用了

<?xml version="1.0" encoding="UTF-8"?>
<project mlns="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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.7.2</version>
    </parent>
    <groupId>org.example</groupId>
    <artifactId>myapp</artifactId>
    <version>1.0-SNAPSHOT</version> 
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--导入自定义的starter-->
        <dependency>
            <groupId>com.malguy</groupId>
            <artifactId>hello-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>
server:
  port:8080
hello:
  name: lihua
  address: beijing
@RestController
@RequestMapping("/hello")
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/say")
    public String sayHello(){
        return helloService.sayHello();
    }
}
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

自定义starter案例二:案例一的基础上添加拦截器,实现记录日志功能

依赖

<?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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.7.2</version>
        <relativePath/>
    </parent>
    <groupId>com.malguy</groupId>
    <artifactId>hello-spring-boot-starter</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
    </dependencies>
</project>

自定义MyLog注解

/**
 * 自定义日志注解
 */
@Target(ElementType.METHOD)//只能加在方法上
@Retention(RetentionPolicy.RUNTIME)//在运行时生效
public @interface MyLog {
    /**
     * 方法描述
     */
    String desc() default "";
}

创建拦截器对象MyLogInterceptor

/**
 * 自定义日志拦截器
 */
public class MyLogInterceptor extends HandlerInterceptorAdapter {
    private static final ThreadLocal<Long> startTimeThreadLocal=
            new ThreadLocal<>(); //记录时间的毫秒值
    //在controller方法执行前执行
    @Override
    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);//方法上获取mylog注解
        if(myLog!=null){
            //当前拦截的方法上加了MyLog注解
            long startTime = System.currentTimeMillis();//获取当前时间(毫秒)
            startTimeThreadLocal.set(startTime);
        }
        return true;
    }
    //在controller方法执行后执行
    @Override
    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);//方法上获取mylog注解
        if(myLog!=null){
            //当前拦截的方法上加了MyLog注解
            Long startTime = startTimeThreadLocal.get();
            long endTime = System.currentTimeMillis();//获取当前时间(毫秒)
            long optTime=endTime-startTime;//计算controller方法执行时间
            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);
            System.out.println("方法执行时间: "+optTime+"ms");
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}

自动配置类自动实例化拦截器对象(注册为bean)

@Configuration
public class MyLogAutoConfiguration implements WebMvcConfigurer {
    //注册自定义日志拦截器 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyLogInterceptor());
    }
}

spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.malguy.config.HelloServiceAutoConfiguration,\
com.malguy.config.MyLogAutoConfiguration

重新打包install,在myapp的controller方法上加注解,测试

@RestController
@RequestMapping("/hello")
public class HelloController {
    @Autowired
    private HelloService helloService;
    @GetMapping("/say")
    @MyLog(desc="sayHello方法")
    public String sayHello(){
        return helloService.sayHello();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鸟malred

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值