1. 编写UserService的接口
package com.zslaa.service;
public interface UserService {
public void save(String name);
public void update();
}
2.编写UserServiceImpl的实现
package com.zslaa.service.impl;
import com.zslaa.service.UserService;
public class UserServiceImpl implements UserService {
@Override
public void save(String name) {
System.out.println("执行save方法,name为:"+name);
}
@Override
public void update() {
System.out.println("执行update方法");
}
}
3.编写AOP注解的切面类
package com.zslaa.aspect;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class MyAspect {
@Before(value="execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void writeLog(){
System.out.println("SpringAOP注解记录日志");
}
}
4.启用@AspectJ的支持
说明:@AspectJ使用了Java 5的注解,可以将切面声明为普通的Java类。@AspectJ样式在AspectJ 5发布的AspectJ project部分中被引入。Spring 2.0使用了和AspectJ 5一样的注解,并使用AspectJ来做切入点解析和匹配。但是,AOP在运行时仍旧是纯的Spring AOP,并不依赖于AspectJ的编译器或者织入器(weaver)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!-- 基于AspectJ的spring的AOP编写之XML方式 -->
<!-- 1.创建目标对象 -->
<bean id="userService" class="com.zslaa.service.impl.UserServiceImpl"/>
<!-- 2.创建切面类对象 -->
<bean id="myAspect" class="com.zslaa.aspect.MyAspect"/>
<!-- 开启SpringAOP注解功能 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
4.编写测试类
package com.zslaa.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.zslaa.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo1 {
@Resource
private CustomerService customerService;
@Test
public void test1(){
customerService.update();
}
}
6.运行结果