1、spring 相关的jar包,此处不做详细处理
2、定义切面的横切点
package com.spring.knights;
public class Minstrel {
/**
* 切面开始方法
*/
public void singBeforeQuest(){
System.out.println("Minstrel....singBeforeQuest....begain");
}
/**
* 界面的结束方法
*/
public void singAfterQuest(){
System.out.println("Minstrel....singAfterQuest....after");
}
}
3、定义切面的测试类
public class BraveKnight {
private Quest quest;
//构造函数
public BraveKnight(Quest quest){
this.quest= quest;
}
//无参构造函数
public BraveKnight(){
}
//需要测试的方法
public void embarkOnQuest(){
quest.embark();
}
}
4、定义切面的调用方法
public class Quest {
//测试调用的方法
public void embark(){
System.out.println("Quest....embark...going");
}
}
5、spring 的相关配置
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
default-lazy-init="true">
<!-- 注入 quest -->
<beanid="quest"class="com.spring.knights.Quest"></bean>
<!-- 注入 minstrel -->
<beanid="minstrel"class="com.spring.knights.Minstrel"></bean>
<!-- 构造函数创建实例进行注入 -->
<beanid="knight"class="com.spring.knights.BraveKnight">
<constructor-argref="quest"></constructor-arg>
</bean>
<!-- 定义aop切面 -->
<aop:config>
<aop:aspect ref="minstrel">
<aop:pointcut expression="execution(* *.embarkOnQuest(..))"id="embark"/>
<aop:before method="singBeforeQuest"pointcut-ref="embark"/>
<aop:after method="singAfterQuest"pointcut-ref="embark"/>
</aop:aspect>
</aop:config>
</beans>
6、spring 测试类
public class SlayDragonQuest {
public static void main(String[]args)throws InterruptedException {
GenericXmlApplicationContextcontext = newGenericXmlApplicationContext();
context.setValidating(false);
//加载spring配置文件
context.load("classpath*:applicationContext*.xml");
//spring容器进行初始化
context.refresh();
//控制反转,从spring容器中获取bean实例
BraveKnightbk = (BraveKnight) context.getBean(BraveKnight.class);
while (true) {
bk.embarkOnQuest();
Thread.sleep(10000);
}
}
}