AOP 即 Aspect Oriented Program 面向切面编程
首先,在面向切面编程的思想里面,把功能分为核心业务功能,和周边功能。
所谓的核心业务,比如登陆,增加数据,删除数据都叫核心业务
所谓的周边功能,比如性能统计,日志,事务管理等等
周边功能在 Spring 的面向切面编程 AOP 思想里,即被定义为切面
在面向切面编程 AOP 的思想里面,核心业务功能和切面功能分别独立进行开发
然后把切面功能和核心业务功能 "编织" 在一起,这就叫 AOP
首先我们编写applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.li.aspect"/>
<context:component-scan base-package="com.li.service"/><!--扫描包 com.how2java.aspect 和 com.how2java.service,定位业务类和切面类-->
<aop:aspectj-autoproxy/><!--找到被注解了的切面类,进行切面配置-->
</beans>
新建一个com.li.test包,然后在下面新建一个ProductService.java类
package com.li.service;
import org.springframework.stereotype.Component;
@Component("s")
public class ProductService {
public void doSomeService(){
System.out.println("doSomeService");
}
}
新建一个com.li.aspect包,在下面新建一个loggerAspect.java类
package com.li.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component//表示此类是bean
@Aspect//表示为切面
public class LoggerAspect {
@Around(value="execution(* com.li.service.ProductService.*(..))")//表示可以用ProductService里的所有方法
public Object log(ProceedingJoinPoint joinpoint) throws Throwable {
System.out.println("start log:"+joinpoint.getSignature().getName());
Object object =joinpoint.proceed();
System.out.println("end log:"+joinpoint.getSignature().getName());
return object;
}
}
最后再新建一个TestService类
package com.li.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import com.li.service.*;
public class TestService {
public static void main(String args[]){
ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{
"applicationContext.xml"
});
ProductService service=(ProductService)context.getBean("s");
service.doSomeService();
}
}
最后输出的结果如下

好了,这次就到这里啦,这只是spring的Aop,按照步骤一步一步来肯定没问题的
有疑问的话可以联系QQ 2321591758
个人博客地址 www.imlowliness.club

1346

被折叠的 条评论
为什么被折叠?



