原创转载请注明出处:http://agilestyle.iteye.com/admin/blogs/2325718
Project Directory
Maven Dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.fool.springaop</groupId> <artifactId>springaop</artifactId> <name>springaop</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <org.springframework-version>4.2.8.RELEASE</org.springframework-version> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework-version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <!-- @Inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.10</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.3.11.v20160721</version> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <httpConnector> <port>8888</port> </httpConnector> <webApp> <contextPath>/springaop</contextPath> </webApp> </configuration> </plugin> </plugins> </build> </project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
root-context.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"> <!-- Root Context: defines shared resources visible to all other web components --> </beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables Spring AOP --> <aop:aspectj-autoproxy /> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> <context:component-scan base-package="org.fool.springaop" /> </beans:beans>
IUserService.java
package org.fool.springaop.service;
public interface IUserService {
void addUser();
String addUserReturnValue();
void addUserThrowException() throws Exception;
void addUserAround(String name);
}
UserService.java
package org.fool.springaop.service.impl;
import org.fool.springaop.service.IUserService;
import org.springframework.stereotype.Service;
@Service
public class UserService implements IUserService {
@Override
public void addUser() {
System.out.println("addUser() invoked...");
}
@Override
public String addUserReturnValue() {
System.out.println("addUserReturnValue() invoked...");
return "200";
}
@Override
public void addUserThrowException() throws Exception {
System.out.println("addUserThrowException() invoked...");
throw new Exception();
}
@Override
public void addUserAround(String name) {
System.out.println("addUserAround() invoked..., args: " + name);
}
}
LoggingAspect.java
package org.fool.springaop.aspect;
import java.util.Arrays;
import java.util.Date;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class LoggingAspect {
@Before("execution(* org.fool.springaop.service.IUserService.addUser(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("@Before invoked!!!");
System.out.println("@Before: " + joinPoint.getSignature().getName());
System.out.println("******");
}
@After("execution(* org.fool.springaop.service.IUserService.addUser(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("@After invoked!!!");
System.out.println("@After: " + joinPoint.getSignature().getName());
System.out.println("******");
}
@AfterReturning(value="execution(* org.fool.springaop.service.IUserService.addUserReturnValue(..))", returning="result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("@AfterReturning invoked!!!");
System.out.println("@AfterReturning: " + joinPoint.getSignature().getName());
System.out.println("@AfterRetruning method returned value is: " + result);
System.out.println("******");
}
/*
* 1.环绕方法通知,环绕方法通知要注意必须给出调用之后的返回值,否则被代理的方法会停止调用并返回null,除非你真的打算这么做。
* 2.只有环绕通知才可以使用JoinPoint的子类ProceedingJoinPoint,各连接点类型可以调用代理的方法,并获取、改变返回值。
*/
@Around("execution(* org.fool.springaop.service.IUserService.addUserAround(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("@Around start: " + new Date());
System.out.println("@Around: " + joinPoint.getSignature().getName());
System.out.println("@Around argument: " + Arrays.toString(joinPoint.getArgs()));
Object obj = joinPoint.proceed(joinPoint.getArgs());
System.out.println("@Around end: " + new Date());
System.out.println("******");
return obj;
}
@AfterThrowing(value="execution(* org.fool.springaop.service.IUserService.addUserThrowException(..))", throwing="ex")
public void logAfterThrowing(JoinPoint joinPoint, Throwable ex) {
System.out.println("@AfterThrowing invoked!!!");
System.out.println("@AfterThrowing: " + joinPoint.getSignature().getName());
System.out.println("@AfterThrowing exception: " + ex);
System.out.println("******");
}
}
AopTest.java
package org.fool.springaop.test;
import org.fool.springaop.service.IUserService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AopTest {
private AbstractApplicationContext ctx;
private IUserService userService;
@Before
public void setUp() throws Exception {
ctx = new FileSystemXmlApplicationContext("/src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml");
userService = ctx.getBean(IUserService.class);
}
@After
public void tearDown() throws Exception {
ctx.close();
}
@Test
public void testBeforeAndAfter() throws Exception {
userService.addUser();
}
@Test
public void testAfterReturning() throws Exception {
userService.addUserReturnValue();
}
@Test
public void testAround() throws Exception {
userService.addUserAround("Around Advice");
}
@Test
public void testAfterThrowing() throws Exception {
userService.addUserThrowException();
}
}
Test
testBeforeAndAfter
testAfterReturning
testAround
testAfterThrowing