public interface IProductDao {
public void save();
public void update();
public String delete();
public void find();
}
public class ProductDao implements IProductDao {
public void save() {
System.out.println("ProductDao save.。。。。");
}
public String delete() {
System.out.println("ProductDaoִ delete()。。。。。。");
return "张三";
}
public void update() {
System.out.println("ProductDaoִ updata()。。。。");
}
public void find() {
System.out.println("ProductDaoִ find()。。。。");
// int i = 1/0;
}
}
applicationContext.xml
<!-- 配置@Service包扫描 相当于配置了该包下所有类的<bean> -->
<context:component-scan base-package="com.demo03" />
<!-- 开启aspecj注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<bean id="productDao" class="com.demo03.ProductDao"></bean>
<bean id="aspect" class="com.demo03.MyAspect2"></bean>
切面类:
//注意:@Aspect并不会初始化MyAspect2
//还是得使用xml配置或者@Component等注解初始化MyAspect2
@Aspect
public class MyAspect2 {
@Before(value="execution(* com.demo03.*.save*(..))")
public void before(JoinPoint join) {
System.out.println(join + "在目标方法执行前 before");
String kind = join.getKind();
System.out.println(kind);
}
//配置pointcut
@Pointcut(value="execution(* com.demo03.*.delete(..))")
private void pointcut02(){}
//注意afterReturn有参数,所以@AfterReturning这边要配置 returning
//而且名称要跟afterReturn入参的名称一致,否则会报错
//java.lang.IllegalArgumentException: error at ::0 formal unbound in pointcut
@AfterReturning(value="MyAspect2.pointcut02()",returning="result")
public void afterReturn(Object result) {
System.out.println("在目标方法执行后 afterReturn");
System.out.println("目标方法执行后的结果" + result);
}
}
测试类:
public class AspectTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IProductDao dao = context.getBean(IProductDao.class);
dao.save();
dao.delete();
}
}
结果: