Why AOP?
- 减少代码
- 就是为了更清晰的逻辑,可以让你的业务逻辑去关注自己本身的业务,而不去想一些其他的事情。这些其他的事情包括:安全、事务、日志等。
demo工程如下:
1.定义一个Service基础类。
@Service("math")
public class Math {
public int add(int n1,int n2){
int result = n1 + n2;
System.out.println("result = "+ n1 + "+"+ n2);
return result;
}
public int sub(int n1 ,int n2){
int result = n1 -n2;
System.out.println("result = "+n1 +"-" + n2);
return result;
}
public int mul(int n1,int n2){
int result=n1 * n2;
System.out.println(n1+"X"+n2+"="+result);
return result;
}
public int div(int n1,int n2){
int result=n1/n2;
System.out.println(n1+"/"+n2+"="+result);
return result;
}
}
使用@Service注解标注该类是Service业务类
2. 定义Advice类,通知类。在该类中定义你想要的功能。 也就是上说的安全、事物、日志等。你给先定义好,然后再想用的地方用一下。包含Aspect的一段处理代码
@Component
@Aspect
public class Advices {
@Before("execution(* com.imut.Math.*(..))")
public void before1(JoinPoint jp){
System.out.println("-----先-----");
System.out.println(jp.getSignature().getName());
}
@After("execution(* com.imut.Math.*(..))")
public void after(JoinPoint jp){
System.out.println("-----后-----");
System.out.println("");
}
}
使用@Component注解表名当前是一个组件,@Aspect表名当前是一个切面,
3.定义.xml配置文件
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:component-scan base-package="com.imut"></context:component-scan> <!-- 扫面整个包 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
4.定义Test
public class Test {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("aop01.xml");
Math math = ac.getBean("math", Math.class);
int n1 = 30, n2 = 5;
math.add(n1, n2);
math.sub(n1, n2);
math.mul(n1, n2);
math.div(n1, n2);
System.out.println("ddd");
}
}