Service
package org.zbq.authority;
public interface Service {
public void view();
public void modify();
}
ServiceImpl
package org.zbq.authority;
public class ServiceImpl implements Service {
@Override
public void view() {
System.out.println("用户查看数据");
}
@Override
public void modify() {
System.out.println("用户修改数据");
}
}
Actionpackage org.zbq.authority;
public interface Action {
public void modify();
public void view();
}
ActionImplpackage org.zbq.authority;
public class ActionImpl implements Action {
private Service s;
public void setS(Service s) {
this.s = s;
}
@Override
public void modify() {
s.modify();
}
@Override
public void view() {
s.view();
}
}
AuthorityInterceptor
package org.zbq.authority;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class AuthorityInterceptor implements MethodInterceptor {
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("=================");
String methodName = invocation.getMethod().getName();
if(! "admin".equals(user) && ! "abc".equals(user)){
System.out.println("您没有该权限");
return null;
}else if("abc".equals(user) && "modify".equals(methodName)){
System.out.println("您没有管理员权限");
return null;
}
return invocation.proceed();
}
}
Clientpackage org.zbq.authority;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Client {
public static void main(String[] args) {
ClassPathResource cpr = new ClassPathResource("authority.xml");
XmlBeanFactory factory = new XmlBeanFactory(cpr);
Action action = (Action) factory.getBean("action");
action.view();
action.modify();
}
}
authority.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="serviceTarget" class="org.zbq.authority.ServiceImpl"/>
<bean id="authorityInterceptor" class="org.zbq.authority.AuthorityInterceptor">
<property name="user">
<value>a</value>
</property>
</bean>
<bean id="service"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>org.zbq.authority.Service</value>
</property>
<property name="target">
<ref local="serviceTarget"/>
</property>
<property name="interceptorNames">
<list>
<value>authorityInterceptor</value>
</list>
</property>
</bean>
<bean id="action" class="org.zbq.authority.ActionImpl">
<property name="s">
<ref local="service"/>
</property>
</bean>
</beans>