戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
AOP-XML配置Helloworld
spring应用手册(第四部分)
关于SprngAOP的概念和思想我们在springAOP(Annotation)章节已经全部解释过了,所以本章节主要讲解SpringAOP的XML配置方式。不再赘述概念。
好的,让我们开始搭建springAOP的XML-Hellowrold程序吧。
如果我们要在配置问中配置AOP,则需要Schema-based AOP 支持。我们会在程序的配置文件中直接添加。
再说明一件事,spring是支持annotation和xml混合使用的,本章节我们主要将XML配置AOP,所以我们就全部使用xml方式配置。
创建一个Maven项目,添加如下依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
我们准备一个业务类:
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class MessageBean {
//输出信息的业务方法
public String printMessage(String msg){
System.out.println("MessageBean-printMessage:"+msg);
return msg;
}
}
添加一个Aspect类,注意在XML模式下,我们可以在Aspect类上方注解@Aspect,也可以不注解,完全使用XML配置的方式。这里我们就完全使用XML配置的方法。
我们的Aspect类就是一个普通的javaBean,在其中添加一个前置通知的方法,并且传入Jointpoint参数。
/**
* @author 戴着假发的程序员
* @company http://www.boxuewa.com
* @description
*/
public class DkAspect {
public void before(JoinPoint joinPoint){
System.out.println("前置通知:"+joinPoint);
}
}
添加一个配置文件,在其中添加Schema-based AOP 支持。
<?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">
<!-- 开始Aspect支持 -->
<!-- 这里的属性expose-proxy和proxy-target-class默认就是false -->
<aop:aspectj-autoproxy expose-proxy="false" proxy-target-class="false"/>
<!-- 注册Aspect类 -->
<bean id="dkAspcet" class="com.st.aspects.DkAspect"/>
<!-- 注册我们的业务类 -->
<bean id="msgService" class="com.st.beans.MessageBean"/>
<!-- AOP配置 -->
<aop:config>
<!-- 申明AspectBean,引用我们注册的dkAspect -->
<aop:aspect id="aspect" ref="dkAspcet">
<!--配置一个前置通知-->
<!-- method指定daAspect类中的前置通知方法,pointcut配置切入点表达式 -->
<aop:before method="before" pointcut="execution(* com.st.beans..*.*(..))"/>
</aop:aspect>
</aop:config>
</beans>
配置的解释已经在配置文件中注释,这里不再赘述。
测试:
@Test
public void testAopByXML() throws IOException {
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
MessageBean bean = ac.getBean(MessageBean.class);
bean.printMessage("假发的穿戴技巧");
}
结果: