0%

SPRING16–AOP编程前置通知XML

前置通知:

实现methodBeforeAdvice接口。该接口中有一个接口before(),在目标方法之前执行,前置通知特点:

  1. 在目标方法之前执行,
  2. 不改变目标方法的执行流程,前置通知代码不能阻止目标方法执行。
  3. 不改变目标方法执行的结果。

列子:

接口类:

1
2
3
4
public interface ISomeService {
public void doFirst();
public void doSecond();
}

实现类:

1
2
3
4
5
6
7
8
9
10
11
public class someServiceImpl implements ISomeService{
public void doFirst() {
// TODO Auto-generated method stub
System.out.println(“doFirst..”);
}
public void doSecond() {
// TODO Auto-generated method stub
System.out.println(“doSecond..”);
}

}

前置接口类:

1
2
3
4
5
6
public class mymethodBeforeAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object target) throws Throwable {
// TODO Auto-generated method stub
System.out.println(“前置通知方法”);
}
}

xml配置:

1
2
3
4
5
6
7
8
9
10
11
<!– 注册目标对象 –>
<bean id=“ISomeService” class=“com.bean.service5.someServiceImpl”></bean>
<!– 注册切面:通知 –>
<bean id=“myadvice” class=“com.bean.service5.mymethodBeforeAdvice”/>
<!– 生成代理对象 –>
<bean id=“serviceProxy” class=“org.springframework.aop.framework.ProxyFactoryBean”>
<!– 指定目标对象 –>
<property name=“target” ref=“ISomeService”></property>
<!– 指定切面–>
<property name=“interceptorNames” value=“myadvice”></property>
</bean>

测试类:

1
2
3
4
5
6
7
@Test
public void test5() {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(“ApplicationContext.xml”);
ISomeService iSomeService=(ISomeService) applicationContext.getBean(“serviceProxy”);
iSomeService.doFirst();
((ClassPathXmlApplicationContext)applicationContext).close();
}