实验报告3-Spring AOP
一、实现思路
利用Spring AOP技术,实现dao层方法的耗时统计。要求:
1、DAO层:在com.sw.dao包下创建接口UserDao.java,定义增删改查四个方法
2、DAO层的实现类:在com.sw.dao包下创建impl包,在impl包下创建UserDao接口的实现类UserDaoImpl,在UserDaoImpl类中实现增删改查四个方法
3、pojo对象XmlAdvice,定义通知
4、配置Spring AOP
5、测试
二、实验步骤
1、新建项目
Name:Experiment3,GroupID:com.sw
引入pom.xml文件、Spring配置文件applicationContext.xml
2、DAO层
com.sw.dao包,UserDao接口
public interface UserDao {
void insert() throws InterruptedException;
void delete() throws InterruptedException;
void update() throws InterruptedException;
void select() throws InterruptedException;
}
com.sw.dao.impl包,UserDao接口的实现类UserDaoImpl
@Repository
public class UserDaoImpl implements UserDao {
Random random = new Random();
public void insert() throws InterruptedException {
Thread.sleep((10+random.nextInt(10))*100);
System.out.println("添加用户信息");
}
public void delete() throws InterruptedException {
Thread.sleep((10+random.nextInt(10))*100);
System.out.println("删除用户信息");
}
public void update() throws InterruptedException {
Thread.sleep((10+random.nextInt(5))*100);
System.out.println("更新用户信息");
}
public void select() throws InterruptedException {
Thread.sleep(random.nextInt(10)*100);
System.out.println("查询用户信息");
}
}
3、定义通知
com.sw.pojo包,XmlAdvice类
public class XmlAdvice {
private Date visitTime; //开始时间
private Logger logger = Logger.getLogger(XmlAdvice.class);
public void before(JoinPoint jp){
visitTime = new Date();//当前时间就是开始访问的从时间
}
public void afterReturning(JoinPoint jp){
long time = new Date().getTime() - visitTime.getTime(); //获取访问的时长
String methodName = jp.getSignature().getName(); //获取访问的方法的名称
//方法全路径
String method = jp.getTarget().getClass().getName() + "." + methodName;
logger.info(method+"方法,耗时:"+time+"毫秒");
}
}
4、配置Spring AOP
applicationContext.xml
<!--使用context命名空间,在配置文件中开启相应的注解处理器-->
<context:component-scan base-package="com.sw"/>
<!--注册Bean-->
<bean id="xmlAdvice" class="com.sw.pojo.XmlAdvice"/>
<!--配置Spring AOP-->
<aop:config>
<!--指定切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.sw.dao.impl.*.*(..))"/>
<!--指定切面-->
<aop:aspect ref="xmlAdvice">
<!--指定前置通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<!--指定返回通知-->
<aop:after-returning method="afterReturning" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
6、测试
com.sw.dao包,UserDaoImpl类方法创建测试,右键→Generate→Test
public class UserDaoImplTest {
private ClassPathXmlApplicationContext applicationContext = null;
private UserDao userDao = null;
@Before
public void setUp() throws Exception {
applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
userDao = applicationContext.getBean("userDaoImpl", UserDao.class);
}
@Test
public void insert() throws InterruptedException {
userDao.insert();
}
@Test
public void delete() throws InterruptedException {
userDao.delete();
}
@Test
public void update() throws InterruptedException {
userDao.update();
}
@Test
public void select() throws InterruptedException {
userDao.select();
}
}