这篇博客主要是String学习笔记(三)——AOP的一个补充。
1、在Spring核心配置中,开启AOP操作
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here -->
<!-- 配置对象 -->
<bean id="book" class="com.jiayifan.aop.Book"></bean>
<bean id="mybook" class="com.jiayifan.aop.MyBook"></bean>
<!-- 开启AOP操作 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
2、为增强类添加注解
package com.jiayifan.aopanno;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//增强类
@Aspect
public class MyBook1 {
@Before(value="execution(* com.jiayifan.aopanno.Book1.*(..))")
public void before() {
System.out.println("anno before增强.....");
}
@After(value="execution(* com.jiayifan.aopanno.Book1.*(..))")
public void after() {
System.out.println("anno after增强.....");
}
@Around(value="execution(* com.jiayifan.aopanno.Book1.*(..))")
public void around(ProceedingJoinPoint p) throws Throwable {
//方法之前
System.out.println("anno before.....");
//执行被增强的方法
p.proceed();
//方法之后
System.out.println("anno after......");
}
}
3、运行
ApplicationContext context =
new ClassPathXmlApplicationContext("SpringAOPAnno.xml");
Book1 b = (Book1) context.getBean("book1");
b.add();