SpringBoot 自定义Annotation

本文介绍了如何在SpringBoot应用中创建并使用自定义Annotation,结合AOP实现特定逻辑。首先在Maven pom.xml文件中添加了Spring AOP和AspectJ的依赖,接着定义了一个名为`SingleLocalCache`的注解,用于标记需要缓存结果的方法。然后创建了一个切面类`SingleLocalCacheAspect`,通过`@Before`、`@AfterReturning`和`@Around`注解在方法执行前后插入自定义逻辑。最后在`TestController`中展示了如何使用这个自定义注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Maven pom.xml 文件添加AOP相关的jar包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.1.RELEASE</version> <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.12</version> <scope>compile</scope>
        </dependency>

2. 自定义Annotation

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)  
public @interface SingleLocalCache {
    
    boolean cache() default false;    
    
    String key();

}

 

3. 写一个切面编程的方法来实现你想要的逻辑

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SingleLocalCacheAspect {
    // 在方法执行前执行
    @Before("@annotation(com.cisco.webex.config.SingleLocalCache)")
    public Object beforeExecute(JoinPoint joinPoint) {
            //MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //Method method = signature.getMethod();
            return null;
    }
     //方法返回后执行
    @AfterReturning(value = "@annotation(com.cisco.webex.config.SingleLocalCache)",
            returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("=====after return===");
        System.out.println("result: " + result.toString());
    }
    //同时处理方法执行前和执行后
    @Around("@annotation(com.cisco.webex.config.SingleLocalCache)")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

         //这一行会执行你的方法

         joinPoint.proceed();

        long timeTaken = System.currentTimeMillis() - startTime;
    }
  
}

4. 接下来具体使用自定义的Annotation

@CrossOrigin
@RestController
public class TestController {
    
    @RequestMapping(method = RequestMethod.GET, value="/test")
    @SingleLocalCache(cache=true,key="test")
    public String getSiteName(@RequestParam(value = "test") String test) {
         return null;
    }
  
    
}

 

参考文章

https://docs.spring.io/spring/docs/2.5.x/reference/aop.html

http://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop

https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations

 

 

 

### 实现Spring Boot自定义配置和组件 #### 使用`@Value`注解获取单个配置属性 对于简单的场景,可以直接利用`@Value`注解来注入application.properties或application.yml文件里的单一配置项到程序变量中。例如: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SimpleConfig { @Value("${server.port}") private int port; public int getPort(){ return port; } } ``` 此方法适用于只需要访问少量配置参数的情况[^2]。 #### 利用`@ConfigurationProperties`绑定多个配置属性至JavaBean 当存在一组关联紧密的配置选项时,推荐采用`@ConfigurationProperties`的方式将其映射成一个POJO类实例。这不仅提高了代码可维护性和整洁度,而且支持更复杂的验证逻辑以及类型安全的数据结构化管理。 ```java @ConfigurationProperties(prefix = "my") public class MyProperties { private String name = "my-spring-boot-starter"; private String type = "default"; // getters and setters... } ``` 为了使上述配置生效,在主应用类或其他配置类上需添加@EnableConfigurationProperties(MyProperties.class),从而激活该功能并允许容器扫描此类作为bean注册进上下文中[^5]。 #### 创建自定义Starter模块提供便捷集成能力 如果希望封装一套通用解决方案供其他微服务调用,则可以考虑构建自己的starter库。通过这种方式,使用者仅需引入依赖即可获得预设好的一系列默认行为和服务发现机制,极大地方便了跨项目的统一管理和部署工作流优化。 在Maven工程下新建module命名为spring-boot-starter-custom,并编写必要的自动化装配规则与条件判断语句,最终打包发布给下游消费者使用[^3]。 #### 自动生成元数据描述文档辅助IDE提示补全 为了让开发者更好地理解和运用这些外部化的设置值,还可以借助META-INF/additional-spring-configuration-metadata.json文件记录详细的字段说明文字、范围约束等信息。这样做有助于提高开发效率的同时减少人为错误的发生概率[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值