class MyThrowsAdvice
package com.aop05;
import org.springframework.aop.ThrowsAdvice;
//异常通知
public class MyThrowsAdvice implements ThrowsAdvice {
//当目标方法抛出指定的异常类型时,执行该方法
public void afterThrowing(UserException ex) {
System.out.println("发生用户名异常 ex = " + ex.getMessage());
}
public void afterThrowing(PasswordException ex) {
System.out.println("发生密码异常 ex = " + ex.getMessage());
}
}
class MyTest
package com.aop05;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test01() {
String resource = "com/aop05/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
ISomeService service = (ISomeService) ac.getBean("serviceProxy");
try {
service.login("beijingaa", "111222");
} catch (UserException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
}
}
class SomeServiceImpl
package com.aop05;
public class SomeServiceImpl implements ISomeService {
@Override
public boolean login(String userName, String password)
throws UserException {
if (!"beijing".equals(userName)) {
throw new UserNameException("用户名输入错误!");
}
if (!"111".equals(password)) {
throw new PasswordException("密码输入错误!");
}
return true;
}
}
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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 注册目标对象 -->
<bean id="someService" class="com.aop05.SomeServiceImpl"/>
<!-- 注册切面 -->
<bean id="myAdvice" class="com.aop05.MyThrowsAdvice"/>
<!-- 生成代理对象 -->
<bean id="serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 指定目标对象 -->
<property name="target" ref="someService"/>
<!-- 指定切面 -->
<property name="interceptorNames" value="myAdvice"/>
</bean>
</beans>