aop-异常通知

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值