接口:
package com.jzq.spring;
public interface UserManager {
public void addUser(String username,String password);
public void deleteUser(int id);
public void modifyUser(int id,String username,String password);
public String findUserById(int id);
}
实现类:
package com.jzq.spring;
public class UserManagerImpl implements UserManager {
@Override
public void addUser(String username, String password) {
System.out.println("------UserManagerImpl.addUser()-----");
}
@Override
public void deleteUser(int id) {
System.out.println("--------UserManagerImpl.deleteUser()-------");
}
@Override
public String findUserById(int id) {
System.out.println("--------UserManagerImpl.findUser()----------");
return null;
}
@Override
public void modifyUser(int id, String username, String password) {
System.out.println("--------deleteUser()-------");
}
}
切入面:
package com.jzq.spring;
public class SecurityHandler {
private void checkSecurity()
{
System.out.println("---------checkSecurity()------------");
}
}
配置:
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="securityHandler" class="com.jzq.spring.SecurityHandler"/>
<bean id="userManager" class="com.jzq.spring.UserManagerImpl"/>
<!-- aop的配置 -->
<aop:config>
<!-- 定义切面 -->
<aop:aspect id="security" ref="securityHandler">
<!-- 定义切面中的pointcut -->
<aop:pointcut id="allAddMethod" expression="execution(* add*(..))"/>
<!-- 指定advice及应用到哪个pointcut -->
<aop:before method="checkSecurity" point-ref="allAddMethod"/>
</aop:aspect>
</aop:config>
</beans>
客户端:
package com.jzq.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String args[])
{
BeanFactory factory=new ClassPathXmlApplicationContext("applicationContext.xml");
//注入UserManager的时候发现类中存在切面中声明的方法,故会生成一个动态代理类
UserManager userManager=(UserManager)factory.getBean("userManager");
//当调用该方法的时候会根据spring配置来调用方法
userManager.addUser("张三", "123");
}
}
当userManager.addUser()根据配置执行了织入方法,如果此时想得到addUser方法中的参数,那么在切入面中的方法模块中添加参数JoinPoint
package com.jzq.spring;
import org.aspectj.lang.JoinPoint;
public class SecurityHandler {
private void checkSecurity(JoinPoint joinPoint)
{
Object[] args=joinPoint.getArgs();
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
//得到方法名
System.out.println(joinPoint.getSignature().getName());
System.out.println("---------checkSecurity()------------");
}
}
jdk只能对实现了接口的类生成动态代理