基于aspectj的advice实现

版权声明:本文为博主原创文章,遵循 CC 4.0 BY 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/drxRose/article/details/100574243
siye@r480:~/svlution/workspace/springaop4322$ tree src/
src/
├── main
│   ├── java
│   │   ├── log4j.properties
│   │   └── ocn
│   │       └── site
│   │           └── springaop
│   │               ├── advice
│   │               │   └── LogUser.java
│   │               ├── setup
│   │               │   └── Appconfig.java
│   │               └── target
│   │                   └── User.java
│   └── resources
└── test
    ├── java
    │   └── ocn
    │       └── site
    │           └── springaop
    │               └── target
    │                   └── Runtest.java
    └── resources
        └── config
            └── application.xml

17 directories, 6 files
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.22.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.22.RELEASE</version>
    <scope>test</scope>
</dependency>
package ocn.site.springaop.advice;

import org.apache.log4j.Logger;
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;

// 测试基于xml-config的风格时,若是标记了该注解@Aspect
// 即使是没有开启注解扫描的功能,也会执行两次通知。原因待定。
// 在基于java-config风格的配置中,官方文档明确指出,需要标记@Component注解,否则无法正常工作。
//@Aspect // 此注解是java-config声明切面的方式
@SuppressWarnings("unused")
@Component
public class LogUser {

	private final Logger logger = Logger.getLogger(this.getClass());

	@Before("execution(public void ocn.site.springaop.target.User.handlerBefore())")
	public void beforeAdvice() {
		logger.info("before advice");
	}

	@After("execution(public void ocn.site.springaop.target.User.handlerAfter())")
	public void afterAdvice() {
		logger.info("after advice");
	}

	@AfterReturning(pointcut = "execution(public * ocn.site.springaop.target.User.handlerReturning())", returning = "value")
	public void returningAdvice(String value) {
		logger.info("returning advice ===>>" + value);
	}

	@AfterThrowing(pointcut = "execution(public void ocn.site.springaop.target.User.handlerThrowing())", throwing = "ex")
	public void throwingAdvice(Exception ex) {
		logger.info("throwing advice ===>>" + ex.toString());
	}

	@Around("execution(public void ocn.site.springaop.target.User.handlerAround())")
	public void aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable {
		logger.info("handler start");
		joinpoint.proceed();
		logger.info("handler ending");
	}
}
package ocn.site.springaop.setup;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan({ "ocn.site.springaop.advice", "ocn.site.springaop.target" })
@EnableAspectJAutoProxy(proxyTargetClass = true) // java-config支持aspectj配置方式
public class Appconfig {

}
package ocn.site.springaop.target;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public class User {

	private final Logger logger = Logger.getLogger(this.getClass());
	private final Class<?>[] nullcls = new Class<?>[] {};

	public void handlerBefore() throws Exception {
		logger.info(this.getClass().getMethod("handlerBefore", nullcls));
	}

	public void handlerAfter() throws Exception {
		logger.info(this.getClass().getMethod("handlerAfter", nullcls));
	}

	public String handlerReturning() throws Exception {
		logger.info(this.getClass().getMethod("handlerReturning", nullcls));
		return "0";
	}

	public void handlerThrowing() throws Exception {
		logger.info(this.getClass().getMethod("handlerThrowing", nullcls));
		throw new NullPointerException();
	}

	public void handlerAround() throws Exception {
		logger.info(this.getClass().getMethod("handlerAround", nullcls));
	}

}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 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.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

	<!--xml-config开启aspectj支持的方式 -->
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

	<bean class="ocn.site.springaop.target.User"></bean>
	<bean id="logUser" class="ocn.site.springaop.advice.LogUser"></bean>

	<aop:config>
		<aop:aspect ref="logUser"><!--此为xml-config声明切面的方式。 -->
			<aop:before method="beforeAdvice"
				pointcut="execution(public void ocn.site.springaop.target.User.handlerBefore())" />
			<aop:after method="afterAdvice"
				pointcut="execution(public void ocn.site.springaop.target.User.handlerAfter())" />
			<aop:after-returning method="returningAdvice"
				pointcut="execution(public * ocn.site.springaop.target.User.handlerReturning())" returning="value" />
			<aop:after-throwing method="throwingAdvice"
				pointcut="execution(public void ocn.site.springaop.target.User.handlerThrowing())" throwing="ex" />
			<aop:around method="aroundAdvice"
				pointcut="execution(public void ocn.site.springaop.target.User.handlerAround())" />
		</aop:aspect>
	</aop:config>

</beans>
package ocn.site.springaop.target;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import ocn.site.springaop.setup.Appconfig;

@SuppressWarnings("unused")
@RunWith(SpringRunner.class)
//@ContextConfiguration(classes = Appconfig.class) // used java-config
@ContextConfiguration("classpath:config/application.xml")
public class Runtest {

	private @Autowired User user;

	@Test
	public void before() throws Exception {
		user.handlerBefore();
	}

	@Test
	public void after() throws Exception {
		user.handlerAfter();
	}

	@Test
	public void returning() throws Exception {
		user.handlerReturning();
	}

	@Test
	public void throwing() throws Exception {
		user.handlerThrowing();
	}

	@Test
	public void around() throws Exception {
		user.handlerAround();
	}

}

猜你喜欢

转载自blog.csdn.net/drxRose/article/details/100574243
今日推荐