spring-aop动态代理功能增强步骤(Aspectj)

1.加入Aspectj的maven依赖

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>4.3.19.RELEASE</version>
    </dependency>

2.编写接口(jdk动态代理需要实现接口)

package org.example.service;

public interface SomeService {
    void doSome();
}

3.编写接口实现类并将对象交给Spring容器管理

package org.example.service.impl;

import org.example.service.SomeService;
import org.springframework.stereotype.Component;

@Component("someServiceImpl")
public class SomeServiceImpl implements SomeService {
    @Override
    public void doSome() {
        System.out.println("HelloWorld");
    }
}

4.编写切面 声明切面(@Aspect) 声明切入点(execution(* org.example.service.impl.SomeServiceImpl.doSome(…))) 声明切入时间(@Before) 并将对象交给Spring容器管理

package org.example.util;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component("serviceTools")
@Aspect
public class ServiceTools {
    @Before(value = "execution(* org.example.service.impl.SomeServiceImpl.doSome(..))")
    public void doLog(){
        System.out.println("time:"+new Date());
    }
}

5.配置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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--声明组件扫描器-->
    <context:component-scan base-package="org.example.bean"></context:component-scan>
    <context:component-scan base-package="org.example.service.impl"></context:component-scan>
    <context:component-scan base-package="org.example.util"></context:component-scan>
    <!--开启aop自动代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

6.测试

    @Test
    public void TestAspect(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        SomeService someService = (SomeService) applicationContext.getBean("someServiceImpl");
        someService.doSome();
    }

结果:
time:Mon Mar 01 10:42:17 CST 2021
HelloWorld

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值