首页 > 解决方案 > 在 Spring Boot 应用程序中实例化 @Service @Transactional 类的多个 bean

问题描述

我对 Spring Boot 比较陌生。我正在开发一个 Spring Boot 应用程序,我需要为同一个 POJO 注入两个不同的 bean。

截至目前,我有一个服务类如下:

@Service
@Transactional
public class StudentServiceImpl implements StudentService {

  private final StudentHelper studentHelper;
  private final Validator validator;


  public StudentServiceImpl(
      StudentHelper studentHelper,
      Validator validator) {
    this.studentHelper = studentHelper;
    this.validator = validator;
  }

  @Override
  public List<Student> generateReport(String courseId) {
     ...
     if(validator != null) {
         validator.validate(courseId);
     }
     ...
  }

现在,我想为同一个 POJO 实例化两个不同的 bean:StudentServiceImpl一个具有正确的验证器,另一个具有一个为 null 的验证器。实际上StudentServiceImpl 是从两个流程中使用的:一个,从需要验证器的资源调用,另一个,从不需要验证器的调度程序调用。

在这方面,我已经看到了多个示例,但我不知道如何制作两个 bean,其中一个用作上述事务服务类,另一个用作简单组件。

基本上,我可以弄清楚,我必须编写如下配置:

@Configuration
public class StudentServiceConfig {

    @Bean   //THIS BEAN IS TO BE USED AS TRANSACTIONAL SERVICE AS MENTIONED ABOVE
    public StudentServiceImpl studentServiceOne(StudentHelper helper, Validator validator) {
        return new StudentServiceImpl(helper, validator);
    }

    @Bean
    public StudentServiceImpl studentServiceTwo(StudentHelper helper) {
        return new StudentServiceImpl(helper, null);
    }
}

在这里,正如我上面提到的,我没有得到任何关于如何将 bean 制作为 的任何线索,该 bean@Service @Transactional将从资源中调用。有人可以帮忙吗?谢谢。

标签: javaspringspring-bootspring-annotations

解决方案


您不需要在类上声明 @Service,因为当您没有 @Bean 配置时,它用于自动检测 bean。

对于事务,您可以从类中省略@Transactional,并通过在添加@Bean 声明的同时手动创建代理类来添加事务来实现相同的功能。参考以下:

Spring @Transactional on @Bean 声明而不是类实现


推荐阅读