Spring AOP 注解配置方式和XML配置方式

本文详细介绍Spring AOP(面向切面编程)的使用方法,包括基于注解和XML配置的AOP实现,涵盖切点、通知类型(如Before、After、Around)、引入、多切面的配置及执行顺序等内容。

jar包

拿接口配置切点时,要注意execution里的路径

一.  @Aspect 注解配置

  • @component注解注释bean
  • @aspect注解注释 切面类
  • <context:component-scan base-package="com.qyc.aop"></context:component-scan> 开启注解扫描
  • <aop:aspectj-autoproxy ></aop:aspectj-autoproxy>  开启aop注解方式
  • (ps:jdk动态代理时,invoke参数是真实对象,所以需要在类里定义一个object)
<?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:context="http://www.springframework.org/schema/context"
    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
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<context:component-scan base-package="com.qyc.aop"></context:component-scan>
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
</beans>
package com.qyc.aop;

import org.springframework.stereotype.Component;

@Component
public class ComponentMethod {
		public void say() {
			System.out.println("我是切点方法!");
		}
}
package com.qyc.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AspectClass {
	@Pointcut("execution(* com.qyc.aop.ComponentMethod.say(..))")
	public void saying() {
		
	}
	@Before("saying()")
	public void before() {
		System.out.println("准备");
	}
	@After("saying()")
	public void	after() {
		System.out.println("完成");
	}

}
package com.qyc.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		ComponentMethod componentMethod = applicationContext.getBean(ComponentMethod.class);
		componentMethod.say();
	}
}

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
准备
我是切点方法!
完成

 

无XML配置

把AspectClass的@component删掉,再建一个AspectStar类

package com.qyc.aop;

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

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.qyc.aop")
public class AspectStart {
	@Bean
	public AspectClass getAspectClass() {
		return new AspectClass();
		
	}
}
package com.qyc.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
	public static void main(String[] args) {

		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AspectStart.class);
		ComponentMethod componentMethod = applicationContext.getBean(ComponentMethod.class);
		componentMethod.say();
	}
}

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
准备
我是切点方法!
完成

环绕 around

注意ProceedingjoinPoint是spring提供的

调用proceed方法,执行目标方法

@Around("saying()")
	public void around(ProceedingJoinPoint pt) {
		System.out.println("环绕前");
		try {
			pt.proceed();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("环绕后");
		
	}

 

 

引入

package com.qyc.aop;

public interface RoleVerifier {
	public boolean verify(Role role);
}
package com.qyc.aop;

public class RoleVerifierImpl implements RoleVerifier{

	@Override
	public boolean verify(Role role) {
		// TODO Auto-generated method stub
		if(role!=null) {
			return true;
		}
		return false;
	}

}

 

//引入,增强bean,将aop代理对象下挂导俩个接口之下,所以可以进行强转,
	@DeclareParents(value="com.qyc.aop.ComponentMethod+",defaultImpl=RoleVerifierImpl.class)
	public RoleVerifier roleVerifier;
package com.qyc.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
	public static void main(String[] args) {
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AspectStart.class);
		ComponentMethod componentMethod = applicationContext.getBean(ComponentMethod.class);
		Role role = new Role("强月城","555");
		RoleVerifier roleVerifier = (RoleVerifier) componentMethod;
		System.out.println(roleVerifier.verify(role));
		componentMethod.say(role);
		
	}
}

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
true
Role [name=强月城, age=555]准备
Role [name=强月城, age=555]你好,我是切点方法!
完成 

 

多切面

  • 用@Order来确定顺序,否则无序
  • AspeConfig要有多个返回aspect的方法
  •  
package com.qyc.MoreAop;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Aspect
@Order(1)
public class Aspect1 {

	@Before("execution(* com.qyc.MoreAop.StudentMethodImpl.printStudent(..)) "+ "&& args(student)")
	public void before(Student student) {
		System.out.println(student.getName()+"Aspect1的before");
	}
	@After("execution(* com.qyc.MoreAop.StudentMethodImpl.printStudent(..)) "+"&& args(student)")
	public void after(Student student) {
		System.out.println(student.getName()+"Aspect1的after");
	}
	
}
package com.qyc.MoreAop;

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

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.qyc.MoreAop")
public class AspectConfig {
	@Bean
	public Aspect1 getAspect1() {
		return new Aspect1();
	}
	@Bean
	public Aspect2 getAspect2() {
		return new Aspect2();
	}
	@Bean
	public Aspect3 getAspect3() {
		return new Aspect3();
	}
}

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestDemo {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AspectConfig.class);
//		ControllerClass controllerClass = applicationContext.getBean(ControllerClass.class);
		StudentMethod controllerClass = applicationContext.getBean(StudentMethod.class);
		controllerClass.printStudent(new Student("强月城","2017011418"));
	}
}

强月城Aspect1的before
强月城Aspect2的before
Aspect3的before
Student [name=强月城, id=2017011418]
Aspect3的after
强月城Aspect2的after
强月城Aspect1的after

 

 

 

二. XML文件配置

  • 先定义bean
  • 然后aop:config
  • aop:aspect
  • aop:pointcut   execution(*空格com.qyc.aopXML.Student.say(..))
  • aop:before
<?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:context="http://www.springframework.org/schema/context"
    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
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<!-- <context:component-scan base-package="com.qyc.aop"></context:component-scan> -->
<!-- <aop:aspectj-autoproxy ></aop:aspectj-autoproxy> -->
<bean id="student" class="com.qyc.aopXML.Student"></bean>
<bean id="aspectMethod" class="com.qyc.aopXML.AspectMethod"></bean>
<aop:config>
	<aop:aspect ref="aspectMethod">
		<aop:pointcut expression="execution(* com.qyc.aopXML.Student.say(..))" id="pointcut"/>
		<aop:before method="before" pointcut-ref="pointcut"/>
		<aop:after method="after" pointcut-ref="pointcut"/>
	</aop:aspect>
</aop:config>

</beans>
package com.qyc.aopXML;

public class Student {
	public void say() {
			System.out.println("你好啊,刘琳!");
	}
}
package com.qyc.aopXML;

public class AspectMethod {
	public void before() {
		System.out.println("(。・∀・)ノ゙嗨");
	}

	public void after() {
		System.out.println("( ̄o ̄) . z Z");
	}
}
package com.qyc.aopXML;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDemo {
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		Student student = (Student) applicationContext.getBean("student");
		student.say();
	}
}

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
(。・∀・)ノ゙嗨
你好啊,刘琳!
( ̄o ̄) . z Z

 

 

多切面

  • 导对包

 

<?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:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	 http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/aop 
     http://www.springframework.org/schema/aop/spring-aop.xsd">
     
     
     
<bean id="stu" class="com.qyc.MoreAopXml.Student">
	<property name="name" value="强月城"></property>
	<property name="id" value="2017011418"></property>
</bean>

<bean id="students" class="com.qyc.MoreAopXml.StudentMethodImpl"></bean>

<bean id="aspect1" class="com.qyc.MoreAopXml.Aspect1"></bean>
<bean id="aspect2" class="com.qyc.MoreAopXml.Aspect2"></bean>
<bean id="aspect3" class="com.qyc.MoreAopXml.Aspect3"></bean>
<aop:config>

<aop:aspect ref="aspect1" order="1">
		<aop:before method="before" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..)) and args(student)"/>
		<aop:after method="after" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..)) and args(student)"/>
	</aop:aspect>
	
	<aop:aspect ref="aspect2" order="2">
		<aop:before method="before" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..))"/>
		<aop:after method="after" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..))"/>
	</aop:aspect>
	
	<aop:aspect ref="aspect3" order="3">
		<aop:before method="before" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..))"/>
		<aop:after method="after" pointcut="execution(* com.qyc.MoreAopXml.StudentMethodImpl.showStudnet(..))"/>
	</aop:aspect>
</aop:config>




</beans>

强月城Aspect1的before
DEBUG 11-21 18:56:53,958 Returning cached instance of singleton bean 'aspect2'  (AbstractBeanFactory.java:251) 
Aspect2的before
DEBUG 11-21 18:56:53,958 Returning cached instance of singleton bean 'aspect3'  (AbstractBeanFactory.java:251) 
Aspect3的before
Student [name=强月城, id=2017011418]
DEBUG 11-21 18:56:53,958 Returning cached instance of singleton bean 'aspect3'  (AbstractBeanFactory.java:251) 
Aspect3的after
DEBUG 11-21 18:56:53,958 Returning cached instance of singleton bean 'aspect2'  (AbstractBeanFactory.java:251) 
Aspect2的after
DEBUG 11-21 18:56:53,958 Returning cached instance of singleton bean 'aspect1'  (AbstractBeanFactory.java:251) 
强月城Aspect1的after

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值