一、创建项目
项目名称:spring100807二、添加jar包 com.springsource.org.aopalliance-1.0.0.jar commons-logging.jar junit-4.10.jar log4j.jar spring-aop-3.2.0.RELEASE.jar spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar三、添加配置文件 1.在项目中创建conf目录 /conf 2.在conf目录下添加核心配置文件 配置文件名称: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:context="http://www.springframework.org/schema/context" 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"> </beans>四、创建bean 1.在src下创建接口与实现类 包名:cn.jbit.spring100807.aop 接口名:CustomerService.java public interface CustomerService { public void login(); } 实现类名:CustomerServiceImpl.java public class CustomerServiceImpl implements CustomerService { @Override public void login() { System.out.println("登录方法"); } } 2.创建通知 包名:cn.jbit.spring100807.advice 通知名:MyBeforeAdvice.java public class MyBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] arg1, Object arg2) throws Throwable { method.invoke(arg2, arg1); System.out.println("前置通知"); } } 3.在配置文件中添加配置 <!-- 第一步:配置拦截目标类 --> <bean id="customerservice" class="cn.jbit.spring100807.aop.CustomerServiceImpl"></bean> <!-- 第二步:配置通知 --> <bean id="mybeforeadvice" class="cn.jbit.spring100807.advice.MyBeforeAdvice"></bean> <!-- 第三步:生成代理Bean --> <bean id="customerproxybean" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="cn.jbit.spring100807.aop.CustomerService"></property> <property name="interceptorNames" value="mybeforeadvice"></property> <property name="target" ref="customerservice"></property> </bean>五、测试 1.在项目中创建test目录 /test 2.在test目录下创建包 包名:cn.jbit.spring100807.advice 3.在包下创建测试类 类名:ProxyTest.java 类内容: public class ProxyTest { @Test public void testBefore(){ ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); CustomerService customerService = (CustomerService) context.getBean("customerproxybean"); //调用业务方法 customerService.login(); } }