Spring 中基于 AOP 的 @AspectJ注解实例

时间:2023-03-09 06:19:12
Spring 中基于 AOP 的 @AspectJ注解实例

@AspectJ 作为通过 Java 5 注释注释的普通的 Java 类,它指的是声明 aspects 的一种风格。通过在你的基于架构的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的。

1.第一步:倒入jar包,跟上个例子包是一样的

  • aspectjrt.jar

  • aspectjweaver.jar

  • aspectj.jar

  • aopalliance.jar

2.第二步:创建三个类

  2.1这里是 Logging.java 文件的内容。这实际上是 aspect 模块的一个示例,它定义了在各个点调用的方法。

 package com.spring.aop2;

 import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut; @Aspect // 定义切面
public class Logging {
@Pointcut("execution(* com.spring.aop2.Student.*(..))") // 定义切点
private void selectAll() { }
/**
* 定义通知方法
*/ @Before("selectAll()")
public void beforeAdvice() {
System.out.println("----------beforeAdvice-----------"); } @AfterReturning(pointcut = "selectAll()", returning = "retVal")
public void afterReturningAdvice(Object retVal) {
System.out.println("Returning:" + retVal.toString());
} @AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex) {
System.out.println("There has been an exception: " + ex.toString());
} }

  2.2下面是 Student.java 文件的内容:

 package com.spring.aop2;

 public class Student {
/**
* 定义学生类
*/
private String name;
private Integer age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public void printAdvice() {
System.out.println("name:" + name + ",age:" + age); } }

  2.3下面是 MainApp.java 文件的内容:

 package com.spring.aop2;

 import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
/**
* Spring aop基于注解 配置文件springAop.xml
* author:
* mail:2536201485@qq.com
* 时间:
*/
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring_xml/springAop.xml");
Student student=(Student)applicationContext.getBean("Student");
student.printAdvice();
} }

3.第三步:创建bean文件(上面的头文件在上个例子当中有,这里就省略了)

下面是配置文件 Beans.xml

     <!-- 开启注解      通过aop命名空间的<aop:aspectj-autoproxy
/>声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面-->
<aop:aspectj-autoproxy/>
<!-- 定义切面bean -->
<bean id="Logging" class="com.spring.aop2.Logging"></bean> <!-- 配置bean -->
<bean id="Student" class="com.spring.aop2.Student">
<property name="name" value="张三"></property>
<property name="age" value="23"></property>
</bean>

让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息(其中包含了异常通知):

Spring 中基于 AOP 的 @AspectJ注解实例