【Spring】注解使用篇

  1. 创建自定义注解接口:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
    String value() default "";
}

在这个示例中,我们定义了一个名为CustomAnnotation的自定义注解,并声明了一个名为value的属性。

  1. 创建注解的处理器:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CustomAnnotationAspect {
    
    @Before("@annotation(customAnnotation)")
    public void beforeMethod(JoinPoint joinPoint, CustomAnnotation customAnnotation) {
        String value = customAnnotation.value();
        // 在方法执行前的逻辑处理
        // ...
        System.out.println("Before method execution. Custom annotation value: " + value);
    }
    
    @AfterReturning("@annotation(customAnnotation)")
    public void afterMethod(JoinPoint joinPoint, CustomAnnotation customAnnotation) {
        String value = customAnnotation.value();
        // 在方法执行后的逻辑处理
        // ...
        System.out.println("After method execution. Custom annotation value: " + value);
    }
}

这里使用了Spring的AOP功能来实现注解处理器。@Aspect注解将该类标记为一个切面类,@Component注解将它声明为一个Spring的组件。@Before注解用于声明在被@CustomAnnotation注解标记的方法执行之前要执行的逻辑代码,@AfterReturning注解用于声明在方法执行后要执行的逻辑代码。

  1. 启用注解处理器:

在Spring配置文件(比如applicationContext.xml)中,配置以下内容:

<context:component-scan base-package="com.example.package" />
<aop:aspectj-autoproxy />

<context:component-scan>用于扫描指定包下的组件,将CustomAnnotationAspect类标记为Spring的组件。<aop:aspectj-autoproxy>用于启用注解处理器。

  1. 使用自定义注解:
@CustomAnnotation(value = "customValue")
public void someMethod() {
    // 方法体
}

在需要使用自定义注解的地方,使用@CustomAnnotation进行标注。在这个示例中,我们给someMethod方法添加了@CustomAnnotation注解,并设置了value属性的值为"customValue"。

当调用someMethod方法时,@CustomAnnotation注解的处理器会根据定义的逻辑在方法执行前后进行一些处理。在本例中,处理器会在方法执行前打印出"Before method execution. Custom annotation value: customValue",在方法执行后打印出"After method execution. Custom annotation value: customValue"。

通过以上步骤,我们就实现了在Spring项目中使用自定义注解的功能。这样我们可以在特定的方法上添加自定义注解,并在注解的处理器中定义相应的逻辑来处理这些方法。通过使用注解,我们可以实现一些横切逻辑的集中管理和复用,提高代码的可维护性和可扩展性。

参考资料:

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

newcih

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

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

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

打赏作者

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

抵扣说明:

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

余额充值