`
357029540
  • 浏览: 732644 次
  • 性别: Icon_minigender_1
  • 来自: 重庆
社区版块
存档分类
最新评论

SpringBoot自定义注解作为starter引入pom

阅读更多

 

在我们项目开发工程中大多时候会遇到一些公共的程序代码需要进行集成使用,比如使用一个注解来定义在方法上,当进入该方法时我们可以记录一些日志信息,该日志信息可以记录进入该方法的时间及离开的时间,以及一些参数的验证,下面主要介绍使用拦截器的方式来实现一个注解,通过拦截器来判断如果方法上使用了该注解,那么我们记录进入、离开以及在该方法的执行时长的日志记录。

1.我们创建一个自定义项目取名为testAnnotation,注意的是我这里创建的是pom项目,生成的基本pom文件内容是:

 

<groupId>testAnnotation</groupId>
<artifactId>testAnnotation</artifactId>
<version>1.0-SNAPSHOT</version>

 

 

2.引入SpringBoot相关的配置

 

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

 因为这里使用的是拦截器,所以必须引入spring-boot-starter-web。

 

 

3.创建一个用于测试的注解LoggerAnnotation的注解类

 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description 自定义一个注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggerAnnotation {
}

 

 

4.创建一个拦截器类LoggerInterceptor,该类继承自HandlerInterceptorAdapter,用于处理调用注解后的方法的日志记录。

 

import com.annotation.log.LoggerAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description 通过拦截器的方式实现自定义的日志记录
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter{

    private Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //判断当前注解是否存在
        if(loggerAnnotation != null){
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime",startTime);
            logger.info("进入" + method.getName() + "方法的时间是:" + startTime);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //判断当前注解是否存在
        if(loggerAnnotation != null){
            long endTime = System.currentTimeMillis();
            long startTime = (Long) request.getAttribute("startTime");
            long periodTime = endTime - startTime;
            logger.info("离开" + method.getName() + "方法的时间是:" + endTime);
            logger.info("在" + method.getName() + "方法的时长是:" + periodTime);
        }
    }
}

 

 

5.将拦截器类注入到适配器中,否则不能正常拦截访问。

 

import com.annotation.interceptor.LoggerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description 注册自定义的拦截器
 */
@Configuration
public class InterceptorRegister extends WebMvcConfigurerAdapter {



    @Bean
    public LoggerInterceptor loggerInterceptor(){
        return new LoggerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(loggerInterceptor());
    }

}

 

6.这个是非常重要的一步,不然在其他项目中是无法正常执行自定义的过滤器的,最初我也没有注意,

 

所以在这里纠结了很久,在resources目录下的META-INFO\spring.factories文件中添加

 

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.annotation.common.InterceptorRegister

 如果resources目录下没有上面所说的META-INFO和spring.factories,则自己新建。

 

 

7.打包生成jar到本地的中央仓库,然后就可以引用了。

 

 

我们新建另外一个SpringBoot项目用于测试上面的注解。

 

8.在新项目中引入上面生成的jar:

<dependency>
     <groupId>testAnnotation</groupId>
     <artifactId>testAnnotation</artifactId>
     <version>1.0-SNAPSHOT</version>
</dependency>

 

9.新建一个用于测试自定义注解的restful类:

import com.annotation.log.LoggerAnnotation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/15
 * @description
 */
@RestController
public class AnnotationController {

    @RequestMapping("/annotationTest")
    @LoggerAnnotation
    public void annotationTest() throws InterruptedException {
        Thread.sleep(5000);
    }
}

 

10.启动程序后,通过访问连接地址http://localhost:8080/annotationTest就可以得到以下

的输出结果:

2017-09-15 13:52:27.015  INFO 407336 --- [nio-8080-exec-1] c.a.interceptor.LoggerInterceptor        : 进入annotationTest方法的时间是:1505454747015
2017-09-15 13:52:32.202  INFO 407336 --- [nio-8080-exec-1] c.a.interceptor.LoggerInterceptor        : 离开annotationTest方法的时间是:1505454752202
2017-09-15 13:52:32.202  INFO 407336 --- [nio-8080-exec-1] c.a.interceptor.LoggerInterceptor        : 在annotationTest方法的时长是:5187

 以上就是自定义注解,然后通过pom的方式引入到新项目的过程。

0
0
分享到:
评论

相关推荐

    SpringBoot自定义starter实例代码

    SpringBoot 的强大功能之一是 把常用的场景抽取成了一个个 Starter(场景启动器),我们通过引入 SpringBoot 为我们提供的这些场景启动器,我们再进行少量的配置就能使用相应的功能。但是,SpringBoot 也不能囊括...

    springboot自定义自动装配.rar

    要创建自定义Starter,需编写`pom.xml`文件引入相关依赖,并创建自动配置类。 2. **命名规范**:自定义Starter的Maven模块名通常以`spring-boot-starter-`开头,如`spring-boot-starter-myapp`。 3. **`spring....

    使用了自定义springboot-starter组件的示例项目【study-springboot】

    在本项目【study-springboot】中,我们深入探讨了如何使用自定义的Spring Boot Starter组件来增强应用程序的功能。Spring Boot Starter是Spring Boot生态体系的一部分,它提供了一种简化配置和快速启动新项目的方式...

    SpringBoot使用注解实现 Redis 数据库的切换.zip

    SpringBoot提供了对Redis的自动配置支持,只需要在项目中引入`spring-boot-starter-data-redis`依赖,它会自动配置`RedisConnectionFactory`和`RedisTemplate`等核心组件。在`pom.xml`文件中添加以下依赖: ```xml ...

    自定义springboot-starter项目源码【cwp-spring-boot-starter】

    这个Starter项目提供了自定义的配置和功能,以便用户能够通过简单的引入依赖就能在他们的SpringBoot应用中使用这些功能。 在项目源码中,`pom.xml`是Maven的项目对象模型文件,它是构建项目的关键。这个文件定义了...

    案例实战-SpringBoot3.x自定义封装starter实战

    5. **示例应用**:为了展示starter的使用,通常会提供一个简单的Spring Boot应用,这个应用引入了我们自定义的starter,并展示了如何在实际项目中使用它。 在本案例的"sms-spring-boot-starter"中,我们可以推断这...

    springboot自定义starter

    在Spring Boot框架中,自定义Starter是一种非常实用的技术,它允许开发者创建可重用的模块,以便在多个项目间快速引入和配置依赖。通过创建自定义Starter,我们可以简化项目构建过程,提高代码的可维护性和一致性。...

    SpringBoot Starter模板

    在"SpringBoot Starter模板"中,你将发现一个基本的`pom.xml`文件,这是Maven项目对象模型的配置文件。这个文件定义了项目的依赖树,包括Spring Boot Starter的各个模块。通过合理配置,你可以引入所需的功能模块,...

    my-springboot-starter.zip

    在本压缩包"my-springboot-starter.zip"中,我们有一个自定义的Spring Boot Starter项目,这个Starter是为了帮助开发者更便捷地整合特定功能而设计的。 自定义Spring Boot Starter是Spring Boot生态系统中的一个...

    springboot构建自己的starter.docx

    这意味着当用户在项目中引入我们的 Starter 后,无需进行额外的手动配置即可直接使用 `PersonService`。 #### 工程搭建与依赖管理 为了实现上述目标,首先需要创建一个新的 Maven 工程。下面给出了工程的 `pom.xml`...

    详解使用Spring Boot的AOP处理自定义注解

    在Spring Boot中,使用AOP处理自定义注解需要引入相关的依赖模块。在pom.xml文件中,添加以下依赖项: ``` &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;spring-boot-starter-aop ``` 接下来,创建一个简单...

    自定义 SpringBoot-Starter email-spring-boot-starter.zip

    在使用这个starter时,首先需要在项目的pom.xml或build.gradle文件中引入依赖。对于Maven项目,可以在dependencies节点下添加如下代码: ```xml &lt;groupId&gt;com.yourcompany&lt;/groupId&gt; &lt;artifactId&gt;email-spring-...

    如何自定义一个SpringBoot中的starter代码实例.zip

    使用`@SpringBootTest`和`@Import`注解来加载自定义的starter,然后通过断言来确认预期的bean是否被正确地创建和配置。 8. **发布到Maven仓库** 将`my-starter`模块打包成jar,并上传到你的私有或公共Maven仓库,...

    自定义注解实现缓存机制

    要实现自定义注解缓存机制,我们首先需要引入Spring Data Redis依赖。在`pom.xml`或`build.gradle`中添加对应的依赖项,确保Spring Boot能够与Redis通信。例如,在Maven项目中,可以添加以下依赖: ```xml ...

    Spring boot创建自定义starter的完整步骤

    当你在项目中引入自定义starter时,Spring Boot会读取这个文件,根据配置加载对应的类。在`spring.factories`中,你可以添加自己的自动配置类,以实现特定的功能或集成新的库。 例如,如果你打算创建一个处理JSON...

    springboot starter实现包

    在"springboot starter实现包"的描述中,我们看到它是一个示例应用,很可能是用来展示如何创建和使用自定义的Starter。创建自定义Starter可以让我们封装特定的功能,使代码更整洁,同时方便其他项目复用。这通常包括...

    springboot-task-starter.zip_grandfatherji1_spring_spring task 动态

    在Spring Boot项目中,为了使用Spring Task,我们需要在`pom.xml`中引入`spring-boot-starter-task`依赖。这样,Spring Boot会自动配置Task的相关组件。 ```xml &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;...

    springboot之yml配置文件信息加密.docx

    使用 @RunWith(SpringJUnit4ClassRunner.class) 和 @SpringBootTest(classes= TrustWebApplication.class) 注解来指定 Spring Boot 的启动类。使用 @Autowired 注解来注入 StringEncryptor 接口,使用 encryptPwd() ...

    手写springboot的starter实例.zip

    `formatSpringbootStarter`可能是一个目录,包含了我们的Starter项目的源代码,包括自动配置类、配置属性类以及可能的自定义注解等。我们需要检查这个目录下的文件,理解每个类的作用,并根据项目需求进行调整。 `...

    customize springboot-starter.rar

    在项目中引入自定义的`spring-boot-starter`,只需要在`pom.xml`或`build.gradle`文件中添加依赖,并在`application.properties`或`application.yml`中配置相关的属性。这样,项目就可以利用自定义starter提供的...

Global site tag (gtag.js) - Google Analytics