spring(AOP)多個切面
阿新 • • 發佈:2019-02-14
/**
* 切面:日誌
* @author w7
*
*/
public class Logger {
public void logging(){
System.out.println("logging");
}
}
/**
* 切面:安全框架
* @author w7
*
*/
public class Security {
public void security(){
System.out.println("security");
}
}
/**
* 切面:許可權
* @author w7
*
*/
public class Privilege {
private String access;
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
/**
* 環繞通知方法
*
* @param joinPoint 目標方法,有返回值
* @return
* @throws Throwable
*/
public Object controlTarget(ProceedingJoinPoint joinPoint) throws Throwable{
Object obj = null; //目標方法返回值
if(this.getAccess().equals("admin")){
obj = joinPoint.proceed();//呼叫目標方法
}else{
System.out.println("許可權不足");
}
return obj;
}
}
/**
* 業務介面
* @author w7
*
*/
public interface SalaryManager {
/**
* 檢視工資
*/
public String showSalary();
}
/**
* 目標類:業務實現
* @author w7
*
*/
public class SalaryManagerImpl implements SalaryManager{
public String showSalary() {
System.out.println("正在檢視工資");
return "aaaa";
}
}
/**
* 第二個 環繞通知測試
*
* 如果有多個環繞通知時,則所有環繞通知 執行完畢後,才執行目標方法
* @author w7
*
*/
public class AroundClass {
public void aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable{
System.out.println("----------------");
joinPoint.proceed();
}
}
//xml配置
<bean id="salaryManager" class="com.itheima09.springaop.xml.salary.SalaryManagerImpl"></bean>
<!--
引入多個切面
logger:日誌系統
security:安全框架
privilege:許可權控制
-->
<bean id="logger" class="com.itheima09.springaop.xml.salary.Logger"></bean>
<bean id="security" class="com.itheima09.springaop.xml.salary.Security"></bean>
<bean id="privilege" class="com.itheima09.springaop.xml.salary.Privilege">
<property name="access" value="admin"></property>
</bean>
<!--
多個環繞通知 測試
-->
<bean id="aroundClass" class="com.itheima09.springaop.xml.salary.AroundClass"></bean>
<aop:config>
<aop:pointcut
expression="execution(* com.itheima09.springaop.xml.salary.SalaryManagerImpl.*(..))"
id="perform"/>
<aop:aspect ref="logger">
<aop:before method="logging" pointcut-ref="perform"/>
</aop:aspect>
<aop:aspect ref="security">
<aop:before method="security" pointcut-ref="perform"/>
</aop:aspect>
<aop:aspect ref="privilege">
<aop:around method="controlTarget" pointcut-ref="perform"/>
</aop:aspect>
<aop:aspect ref="aroundClass">
<aop:around method="aroundMethod" pointcut-ref="perform"/>
</aop:aspect>
</aop:config>
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
SalaryManager salaryManager = (SalaryManager)context.getBean("salaryManager");
//執行目標方法
String s = salaryManager.showSalary();
System.out.println(s);
}
結果:
logging
security
---------------- // 第二個環繞通知執行的輸出
正在檢視工資 //目標方法執行結果
null //目標方法返回值