Spring AOP 详解 (二)

2014-11-24 11:36:05 · 作者: · 浏览: 18
ln("AServiceImpl.barA()");
}

public void fooA(String _msg) {
System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
}
}

package com.spring.service;
/**
*接口A的实现类
*/
public class AServiceImpl implements AService {

public void barA() {
System.out.println("AServiceImpl.barA()");
}

public void fooA(String _msg) {
System.out.println("AServiceImpl.fooA(msg:"+_msg+")");
}
}

[java]
package com.spring.service;

/**
* Service类B
*/
public class BServiceImpl {

public void barB(String _msg, int _type) {
System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
if(_type == 1)
throw new IllegalArgumentException("测试异常");
}

public void fooB() {
System.out.println("BServiceImpl.fooB()");
}

}

package com.spring.service;

/**
* Service类B
*/
public class BServiceImpl {

public void barB(String _msg, int _type) {
System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")");
if(_type == 1)
throw new IllegalArgumentException("测试异常");
}

public void fooB() {
System.out.println("BServiceImpl.fooB()");
}

}
ApplicationContext

[java]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-autowire="autodetect">

aspect id="TestAspect" ref="aspectBean">

expression="execution(* com.spring.service.*.*(..))" />











< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-autowire="autodetect">



expression="execution(* com.spring.service.*.*(..))" />









测试类AOPTest

[java]
public class AOPTest extends AbstractDependencyInjectionSpringContextTests {

private AService aService;

private BServiceImpl bService;

protected String[] getConfigLocations() {
String[] configs = new String[] { "/applicationContext.xml"};
return configs;
}


/**
* 测试正常调用
*/
public void testCall()
{
System.out.println("SpringTest JUnit test");
aService.fooA("JUnit test fooA");
aService.barA();
bService.fooB();
bService.barB("JUnit test barB",0);
}

/**
* 测试After-Throwing
*/
public void testThrow()
{
try {
bServic