spring-aop类编写
在spring配置文件中添加配置
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 注册注解处理器(打开注解) -->
<context:annotation-config/>
<!-- 包扫描(告诉spring容器,哪些类中包含有注解) -->
<context:component-scan base-package="com.zl.*"/>
<!-- 注册aop注解处理器:打开aop的注解 :在spring4开始需要添加代理目标类 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
<!-- 将UserMapperImpl交给spring管理:由spring创建当前类的对象 -->
<bean id="userMapper" class="com.zl.mapper.impl.UserMapperImpl" scope="singleton" lazy-init="true" >
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userService" class="com.zl.service.impl.UserServiceImpl">
<!-- 将userDao对象注入到userService对象中 :set方法注入-->
<!-- <property name="userDao" ref="userDao"></property> -->
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="iUserService" class="com.zl.service.impl.IUserServiceImpl" />
<bean id="iUserMapper" class="com.zl.mapper.impl.IUserMapperImpl" >
<!--在spring中使用 JdbcDaoSupport 类需要配置数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="iUserSubjectMapper" class="com.zl.mapper.impl.IUserSubjectMapperImpl" >
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 将AOP的类交给spring管理 -->
<!-- <bean id="myAspect" class="com.isscollege.aspect.MyAspect"></bean> -->
</beans>
编写切面类
package com.zl.aspect;
import com.zl.entity.Users;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
// 能够做到细粒度的拦截---方法级别的拦截
@Component // @Controller,@Service,@Mapper ,不太好划分当前类属于哪一层时使用
// <!-- <bean id="myAspect" class="com.isscollege.aspect.MyAspect"></bean> -->
@Aspect // 标记当前类是一个切面
public class UsersAspect {
//创建一个换行的静态常量
private static final String LINE_SEPARATOR =System.getProperty("line.separator");
// 拦截com.zl.service.impl.UserServiceImpl的所有方法
// @Pointcut(" execution(*
// com.zl.service.impl.UserServiceImpl.*(..))") // 标记此方法为一个切入点
//@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.*(..))") // 拦截所有方法
@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.login(..))") // 只拦截login方法
public void myPointCut(){}
@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.modifyPass(..))") // 只拦截modifyPass方法
public void myModifyPass(){}
@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.getUserScore(..))") // 只拦截getUserScore方法
public void myGetUserScore(){}
@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.regist(..))") // 只拦截regist方法
public void myRegister(){}
@Pointcut(" execution(* com.zl.service.impl.IUserServiceImpl.logout(..))") // 只拦截logout方法
public void myLogout(){}
// @Before("myPointCut()") // 前置通知
public void testBeforeNotice(JoinPoint jp) {
System.out.println("在目标方法执行之前执行。。。");
Object[] args = jp.getArgs();
// for (Object object : args) {
// System.out.println("目标法法的参数为:" + object);
// }
Users user = (Users) args[0];
HttpServletRequest req = (HttpServletRequest) args[1];
String IP = req.getRemoteAddr();
System.out.println("IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统");
}
// @After("myPointCut()") // 最终通知
public void testAfterNotice() {
System.out.println("在目标方法执行之后执行。。。");
}
// @AfterReturning(pointcut = "myPointCut()", returning = "result") // 返回通知
public void testAfterReturnNotice(JoinPoint jp, Object result) {
System.out.println("在目标方法执行完成并在return之后执行。。。");
System.out.println("目标方法返回值" + result);
}
// @AfterThrowing("myPointCut()") // 异常通知
public void testAfterThrowingNotice() {
System.out.println("目标方法出现异常时执行"); // 除了目标方法之外的任何方法出现异常,此方法都不执行
}
@Around("myPointCut()")
public Object testAroundNotice1(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕通知--可能在目标方法执行之前或之后执行--围绕目标方法整个执行");
// Object[] args = pjp.getArgs();
// for (Object object : args) {
// System.out.println("环绕:参数" + object);
// }
// 2监控目标方法执行效率
// long start = System.currentTimeMillis();
// Object obj = pjp.proceed(); // 让目标法法执行
// // ---obj为目标方法的返回值,此方法执行之前的代码会在目标方法执行执行
// long end = System.currentTimeMillis();
// System.out.println("目标方法执行用了" + (end - start) + "毫秒");
// System.out.println("环绕返回值:" + obj);
// Signature signature = pjp.getSignature(); // 方法签名
// Class<? extends Signature> class1 = signature.getClass();
// String name = signature.getName(); // 方法名
// int modifiers = signature.getModifiers(); // 访问修饰符
// String declaringTypeName = signature.getDeclaringTypeName();
// Class declaringType = signature.getDeclaringType(); // 获取对象类型
//
// System.out.println(signature + " 1 " + class1 + " 2 " + name + " 3 "
// + modifiers + " 4 "
// + declaringTypeName + " 5 " + declaringType);
// 日志
Object[] args = pjp.getArgs();
for (Object object : args) {
System.out.println("环绕:参数" + object);
}
Users user= (Users) args[0];
HttpServletRequest req = (HttpServletRequest) args[1];
String IP = req.getRemoteAddr();
Signature signature = pjp.getSignature();
String name = signature.getName();
System.out.println("IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法");
String info = "IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File("E:/log.txt"),true))); //追加模式
bw.write(info+LINE_SEPARATOR);
bw.flush();
bw.close();
System.out.println("执行环绕前····");
Object obj = pjp.proceed(); //执行拦截的方法
System.out.println("执行环绕后····");
return obj;
}
@Around("myModifyPass()")
public Object testAroundNotice2(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
for (Object object : args) {
System.out.println("环绕:参数" + object);
}
HttpServletRequest req = (HttpServletRequest)args[2];
HttpSession session = req.getSession(true);
Users user = (Users)session.getAttribute("user");
String IP = req.getRemoteAddr();
Signature signature = pjp.getSignature(); //获取拦截的对象
String name = signature.getName();
System.out.println("IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法");
String info = "IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File("E:/log.txt"),true))); //追加模式
bw.write(info+LINE_SEPARATOR);
bw.flush();
bw.close();
System.out.println("执行环绕前····");
Object obj = pjp.proceed(); //执行拦截的方法
System.out.println("执行环绕后····");
return obj;
}
@Around("myGetUserScore()")
public Object testAroundNotice3(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
for (Object object : args) {
System.out.println("环绕:参数" + object);
}
HttpServletRequest req = (HttpServletRequest)args[1];
HttpSession session = req.getSession(true);
Users user = (Users)session.getAttribute("user");
String IP = req.getRemoteAddr();
Signature signature = pjp.getSignature(); //获取拦截的对象
String name = signature.getName();
System.out.println("IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法");
String info = "IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File("E:/log.txt"),true))); //追加模式
bw.write(info+LINE_SEPARATOR);
bw.flush();
bw.close();
System.out.println("执行环绕前····");
Object obj = pjp.proceed(); //执行拦截的方法
System.out.println("执行环绕后····");
return obj;
}
@Around("myRegister()")
public Object testAroundNotice4(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
for (Object object : args) {
System.out.println("环绕:参数" + object);
}
HttpServletRequest req = (HttpServletRequest)args[1];
String IP = req.getRemoteAddr();
Signature signature = pjp.getSignature(); //获取拦截的对象
String name = signature.getName();
System.out.println("IP地址为" + IP + "的用户在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "操作了 " + name + " 方法");
String info = "IP地址为" + IP + "的用户在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "操作了 " + name + " 方法";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File("E:/log.txt"),true))); //追加模式
bw.write(info+LINE_SEPARATOR);
bw.flush();
bw.close();
System.out.println("执行环绕前····");
Object obj = pjp.proceed(); //执行拦截的方法
System.out.println("执行环绕后····");
return obj;
}
@Around("myLogout()")
public Object testAroundNotice5(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
for (Object object : args) {
System.out.println("环绕:参数" + object);
}
HttpServletRequest req = (HttpServletRequest)args[1];
HttpSession session = req.getSession(true);
Users user = (Users)session.getAttribute("user");
String IP = req.getRemoteAddr();
Signature signature = pjp.getSignature(); //获取拦截的对象
String name = signature.getName();
System.out.println("IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法");
String info = "IP地址为" + IP + "的用户:" + user.getUsername() + "在"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "登录了系统,操作了 " + name + " 方法";
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File("E:/log.txt"),true))); //追加模式
bw.write(info+LINE_SEPARATOR);
bw.flush();
bw.close();
System.out.println("执行环绕前····");
Object obj = pjp.proceed(); //执行拦截的方法
System.out.println("执行环绕后····");
return obj;
}
}
执行结果: