package com.gqc.aop05;
import org.springframework.aop.ThrowsAdvice;
//异常通知
public class MyThrowsAdvice implements ThrowsAdvice {
// 当目标方法抛出UsernameException异常时,执行当前方法
public void afterThrowing(UserNameExcepiton ex) {
System.out.println("发生用户名异常 ex = " + ex.getMessage());
}
// 当目标方法抛出PasswordException异常时,执行当前方法
public void afterThrowing(PasswordException ex) {
System.out.println("发生密码异常 ex = " + ex.getMessage());
}
// 当目标方法抛出其它异常时,执行当前方法
public void afterThrowing(Exception ex) {
System.out.println("发生异常 ex = " + ex.getMessage());
}
}
package com.gqc.aop05;
import com.gqc.utils.SystemService;
//目标类
public class SomeServiceImpl implements ISomeService {
@Override
public boolean login(String username, String password) throws UserException {
if(!("beijing".equals(username))){
throw new UserNameExcepiton("用户名输错了");
}
if(!"111".equals(password)){
throw new PasswordException("密码输错了");
}
return true;
}
}
<?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.gqc.aop05.SomeServiceImpl"/>
<!-- 注册切面:后置通知 -->
<bean id="myAdvice" class="com.gqc.aop05.MyThrowsAdvice"/>
<!-- 生成代理对象 -->
<bean id="serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 指定目标对象 -->
<property name="target" ref="someService"/>
<!-- <property name="targetName" value="someService"/> -->
<!-- 指定切面 -->
<property name="interceptorNames" value="myAdvice"/>
</bean>
</beans>
package com.gqc.aop05;
//异常分两种
//1)运行时异常 不进行处理也可以编译通过
//若一个类继承RunntimeException 则该异常就是运行时异常
//1)编译时异常(受查异常 Checked Exception) 不进行处理将无法通过编译
//若一个类继承Exception 则该异常就是受查异常
public class UserException extends Exception {
public UserException() {
super();
// TODO Auto-generated constructor stub
}
public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}