Spring的动态代理

本文介绍了一种通过代理类为原始类新增额外功能的方法——面向切面编程(AOP)的应用实例。具体展示了如何使用Spring框架定义接口和服务实现,并通过XML配置来引入额外的功能,如在方法调用前后执行特定操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.概念

通过代理类为原始类新增额外功能

2.编码

定义接口

public interface UserService {
    public void register(User user);

    public boolean login(String name, String password);
}

定义实现类

public class UserServiceImpl implements UserService {

    @Override

    public void register(User user) {

        System.out.println("UserServiceImpl.register 业务运算 + DAO ");

    }

    @Override

    public boolean login(String name, String password) {

        System.out.println("UserServiceImpl.login");

        return true;

    }

}

定义额外功能

参数详解:MethodBeforeAdvice是在原始方法运行之前执行该方法

Method:额外功能所增加给的那个原始方法

Object[]:额外功能所增加给的原始方法的参数

Object:额外功能所曾加给的那个对象

 
public class Before implements MethodBeforeAdvice {
   
    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("-----method before advice log------");
    }
}

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">


    <bean id="userService" class="com.xxx.UserServiceImpl"></bean>

    <bean id="orderService" class="com.xxx.OrderServiceImpl"/>

    <bean id="before" class="com.xxx.Before"/>

    <aop:config proxy-target-class="true">
<!--        所有的方法,都作为切入点,加入额外功能 login register-->
        <aop:pointcut id="pc" expression="execution(* login(..)) or execution(* register(..))"/>
        <!--组装:目的把切入点 与 额外功能进行 整合-->
        <aop:advisor advice-ref="before" pointcut-ref="pc"/>
    </aop:config>

</beans>

结果

public void test2() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
        UserService userService = (UserService) ctx.getBean("userService");
        boolean result = userService.login("suns", "123456");
        userService.register(new User());
    }



-----method before advice log------
UserServiceImpl.login
-----method before advice log------
UserServiceImpl.register 业务运算 + DAO 

Process finished with exit code 0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值