一、spring实现日志AOP的步骤:
首先注意导入一个jar包!
- 在applicationContext.xml中配置扫包
<!-- 扫包,扫描com下的所有类属性注解--> <context:component-scan base-package="com"/>
- <aop:aspectj-autoproxy>:开启aop的自动代理
<!-- 开启aspect自动代理--> <aop:aspectj-autoproxy/>
- 切面类
@Component//spring要管理的话需要把这个类注解成容器 @Aspect//切面类 public class LogAspect { //定义切点:解释:要执行的方法(返回值任意类型 com包下的dao下的所有类下的所有方法(任意参数)) @Pointcut("execution(* com.dao.*.*(..))") public void pointCut(){} //定义通知:解释:切点之前的通知 //前置通知 @Before("pointCut()") public void doBefore(JoinPoint joinPoint){ Date date = new Date(System.currentTimeMillis()); System.out.println("sdfasdfasdfasdfasdfasdfasdf"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String format = sdf1.format(date); System.out.println("开始时间:"+format); System.out.println("joinPoint的getKind:"+joinPoint.getKind()); System.out.println("执行的方法:"+joinPoint.getSignature().getName()); System.out.println("获取joinPoint的类实例:"+joinPoint.getClass().getName()); System.out.println("执行时传递的参数:"+joinPoint.getArgs()); } //后置通知 @After("pointCut()") public void doAfter(JoinPoint joinPoint){ System.out.println("这是个后置通知"); } }
- 注意:这里的规则是调用这个类里面的方法会触发规则,如果是间接调用则不好使!
- execution表达式简单解释:搜索execution表达式
二、spring实现事物AOP的步骤
- 事物 transaction
- 四个特性:
- A:原子性
- C:一致性;
- I:隔离性
- D :永久性
-
声明式事物
- 步骤:
- 开启AOP代理<aop:aspectj-autoproxy/>
- 在配置文件中配置transactionManager事物管理器
- 启动注解驱动:<tx:annotation-driven transaction-manager="transactionManager"/>
- service类的上面或方法上面添加@Transactional注解进行事物标注
- 类上面代表类里的所有方法
- 方法上面代表此方法
- 四个特性:
<!--设置aop方式一、注解声明方式-->
<!-- 开启aspect自动代理-->
<aop:aspectj-autoproxy/>
<!-- 事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 启动注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
之后就是需要在需要事物的类上或方法上写注解@Transctional
-
置入式通知方式
- 不需要在类上写注解
<!-- 设置aop方式二、置入式通知-->
<!-- 开启aspect自动代理-->
<aop:aspectj-autoproxy/>
<!-- 事物管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 设置具体匹配到的方法-->
<tx:method name="add*"/>
<!-- <tx:method name="update*"/>-->
</tx:attributes>
</tx:advice>
<!-- aop设置-->
<aop:config>
<!-- 设置切点-->
<aop:pointcut id="point" expression="execution(* com.service.*.*(..))"/>
<!-- 通知织入-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
</aop:config>