/**
* 切面:日志
* @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>
<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