基于注解的切面实现
以下是使用注解方式实现切面的案例代码:
1. 创建目标类 `MyClass.java`:
public class MyClass {
public void doSomething() {
System.out.println("Doing something...");
}
}
2. 创建切面类 `MyAspect.java`:
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.MyClass.doSomething())")
public void beforeAdvice() {
System.out.println("Before advice executed");
}
}
在上面的代码中,我们使用 `@Aspect` 注解将 `MyAspect` 类标记为切面类,并使用 `@Before` 注解定义了前置通知。通知方法中的切入点表达式指定了要拦截的方法。
3. 创建Spring配置文件 `spring-config.xml`:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.example"/>
</beans>
在上面的配置文件中,我们使用 `<context:component-scan>` 元素开启了注解扫描,指定了要扫描的包。
4. 创建测试类 `Main.java`:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.example.MyClass;
public class Main {
public static void main(String[] args) {
// 加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
// 获取代理对象
MyClass myClass = (MyClass) context.getBean("myClass");
// 调用目标方法
myClass.doSomething();
}
}
在上面的测试类中,我们通过加载Spring配置文件来初始化Spring容器。然后,从容器中获取代理对象 `myClass`,并调用目标方法 `doSomething()`。
当运行测试类时,前置通知 `beforeAdvice()` 将会在目标方法执行前被调用。
这是一个使用注解方式实现切面的简单案例。通过在切面类中使用注解定义切入点和通知,我们可以在目标方法执行前后添加额外的逻辑。