Spring - 拦截 bean 创建并注入自定义代理

作者:编程家 分类: spring 时间:2025-06-04

使用 Spring 框架可以方便地拦截 bean 的创建并注入自定义代理。这种方式可以在 bean 创建的过程中进行一些额外的处理,比如添加日志、实现缓存等功能。本文将详细介绍如何使用 Spring 拦截 bean 创建并注入自定义代理,并通过一个简单的案例代码来演示。

案例代码

假设我们有一个 UserService 接口,其中定义了一个方法 addUser,用于添加用户。我们希望在每次调用该方法时,记录日志。为了实现这个功能,我们可以创建一个代理类 UserServiceProxy,通过拦截 bean 创建并注入自定义代理的方式,将它注入到 Spring 容器中。

java

public interface UserService {

void addUser(String username);

}

public class UserServiceImpl implements UserService {

@Override

public void addUser(String username) {

// 添加用户的具体实现逻辑

System.out.println("添加用户:" + username);

}

}

public class UserServiceProxy implements UserService {

private UserService target;

public UserServiceProxy(UserService target) {

this.target = target;

}

@Override

public void addUser(String username) {

// 在方法调用前添加日志

System.out.println("开始添加用户:" + username);

target.addUser(username);

// 在方法调用后添加日志

System.out.println("成功添加用户:" + username);

}

}

@Configuration

public class AppConfig {

@Bean

public UserService userService() {

return new UserServiceImpl();

}

@Bean

public UserServiceProxy userServiceProxy(UserService userService) {

return new UserServiceProxy(userService);

}

}

public class Main {

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

UserService userService = context.getBean(UserService.class);

userService.addUser("Alice");

}

}

拦截 bean 创建并注入自定义代理

在上述案例代码中,我们首先定义了一个 UserService 接口和其实现类 UserServiceImpl。然后,我们创建了一个 UserServiceProxy 代理类,它实现了 UserService 接口,并在方法调用前后分别记录了日志。

接下来,我们通过 @Configuration 注解的 AppConfig 类来配置 Spring 容器。在该类中,我们使用 @Bean 注解分别创建了 UserService 和 UserServiceProxy 的实例,并将 UserServiceProxy 的实例注入到容器中。

最后,在 Main 类中,我们通过 ApplicationContext 获取了 UserService 的实例,并调用了它的 addUser 方法。由于我们在容器配置中注入了 UserServiceProxy 的实例,所以实际调用的是 UserServiceProxy 的 addUser 方法,从而实现了日志的记录功能。

通过以上案例代码,我们可以看到,使用 Spring 拦截 bean 创建并注入自定义代理可以很方便地实现一些额外的处理逻辑。这种方式可以让我们在不修改原有代码的情况下,对方法进行增强或添加一些额外的功能。这对于日志记录、事务管理等功能的实现非常有用。