SpringAOP 动态代理技术

1.导入AOP相关的坐标

<dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.4</version>
    </dependency>

2.创建目标接口和实现目标类

//实现类 需要增强的方法:
public class ProxyTargetImpl implements ProxyTarget {
    
    
    @Override
    public void save() {
    
    
        System.out.println("ProxyTargetImpl的方法执行了");
    }
}

3.创建切面类 advice 内部有增强方法

//切面类 定义增强方法

public class MyAspect {
    
    
    public void before(){
    
    
        System.out.println("前置增强执行了...");
    }
}

4.将目标类和切面类的对象创建权交给SpringIOC管理

<!--aop配置:把目标对象配进IOC容器-->
    <bean id="proxyTarget" class="com.itcast.aop.ProxyTargetImpl"></bean>
    <!--配置切面-->
    <bean id="myApsect" class="com.itcast.aop.MyAspect"></bean>

5.在applicationContext.xml中配置织入关系

<!--配置织入 告诉spring框架 哪些方法(切点)需要哪些增强-->
    <aop:config>
        <aop:aspect ref="myApsect">
            <aop:before method="before" pointcut="execution(public void com.itcast.aop.ProxyTargetImpl.save())"></aop:before>
        </aop:aspect>
    </aop:config>

6.测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class test {
    
    

    @Autowired
    private ProxyTarget target;

    @Test
    public void test1(){
    
    
        target.save();
    }
}

Guess you like

Origin blog.csdn.net/Fhakjfksakln/article/details/120415952