AOP权限DEMO1: 实体类: package com.etc.entity; import org.aspectj.lang.annotation.Pointcut; public class User implements IUser { public static int NORMAL = 1;//普通用户角色 public static int ADMIN = 2; //管理员角色 private int role; //所属的角色 public int getRole() { return role; } public void setRole(int role) { this.role = role; } public void login() { System.out.println("执行登录了!"); } public void reg() { System.out.println("执行注册了!"); //throw new RuntimeException("注册过程发生异常!"); } } ================================================================ 实体类需实现的接口: package com.etc.entity; //定义用户接口 public interface IUser { void login(); //登录 void reg(); //注册 } ================================================================= 通知类: package com.etc.advice; import java.util.Calendar; import org.aspectj.lang.ProceedingJoinPoint; import com.etc.entity.User; //实现权限校验的通知.规定周三不能登录系统 public class PrivilegeAdvice { public void around(ProceedingJoinPoint point) throws Throwable { //获得该通知被织入的目标对象 User u = (User) point.getTarget(); //1 今天是星期几? Calendar c = Calendar.getInstance(); int day = c.get(Calendar.DAY_OF_WEEK); if((day-1)==5&&u.getRole()==User.ADMIN) { System.out.println("周三普通用户不能登录本系统!"); return; } point.proceed();//允许代码继续往前 } } ================================================================= 配置文件: <?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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 定义1个业务类对象 --> <bean id="user" class="com.etc.entity.User"> <property name="role" value="2"></property> </bean> <!-- 定义1个通知类对象 --> <bean id="myadv2" class="com.etc.advice.PrivilegeAdvice"> </bean> <aop:config> <!-- 配置切点的集合、即切线 --> <aop:pointcut expression="execution(* com.etc.entity.User.*(..))" id="mypc"/> <!-- 配置切入的方向 ,即切面--> <aop:aspect ref="myadv2"> <!-- 前置通知 --> <aop:before method="around" pointcut-ref="mypc"/> </aop:aspect> </aop:config> </beans> =============================================== 测试类: package com.etc.test; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.etc.entity.IUser; public class Test { public static void main(String[] args) { BeanFactory fac = new ClassPathXmlApplicationContext("applicationContext.xml"); IUser u = (IUser) fac.getBean("user"); //执行业务方法 u.login(); System.out.println("====="); try { u.reg(); } catch (Exception e) { } } } =====================================================================