2. 添加.jar包
3. 在src下创建com.xxx.po.Student接口,添加selectStu()、insertStu()方法
4. 在src下创建com.xxx.po.CollegeStudent类,实现Student接口,包含属性:String类型stuNo,stuName和score(Integer)
5. 在src下创建com.xxx.aspect.LogAspect切面,定义环绕通知myAround()。
6. 在src下创建applicationContext.xml文件
7. 在src下创建com.xxx.test.StuTest类,调用selectStu()、insertStu()方法。
//Student.java
package com.xzk.po;
public interface Student {
public void insertUser();
public void selectUser();
}
//CollegeStudent.java
package com.xzk.po;
import org.springframework.stereotype.Repository;
@Repository("student")
public class CollegeStudent implements Student {
private String stuNo;
private String stuName;
private Integer score;
public void insertUser() {
System.out.println("添加用户成功!!!");
}
public void selectUser() {
System.out.println("查找用户成功!!!!");
}
}
//LosAspect.java
package com.xzk.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LosAspect {
@Pointcut("execution(* com.xzk.po.*.*(..))")
private void myPointCut(){}
@Around("myPointCut()")
public Object myAround(ProceedingJoinPoint proceedingJoinPoint)
throws Throwable {
// 开始
System.out.println("环绕开始:执行目标方法之前,模拟开启事务...");
// 执行当前目标方法
Object obj = proceedingJoinPoint.proceed();
// 结束
System.out.println("环绕结束:执行目标方法之后,模拟关闭事务...");
return obj;
}
}
//applicationContext.xml
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 指定需要扫描的包,使注解生效 -->
<context:component-scan base-package="com.xzk" />
<!-- 启动基于注解的声明式AspectJ支持 -->
<aop:aspectj-autoproxy />
</beans>
//StuTest.java
package com.xzk.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xzk.po.Student;
public class StuTest {
public static void main(String args[]) {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext(xmlPath);
Student student = (Student) applicationContext.getBean("student");
System.out.println("徐振凯的实验输出:");
student.insertUser();
student.selectUser();
}
}