【问题标题】:Instantiating multiple beans of the @Service @Transactional class in Spring boot application在 Spring Boot 应用程序中实例化 @Service @Transactional 类的多个 bean
【发布时间】:2021-05-30 14:53:44
【问题描述】:

我对 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 之一作为@Service @Transactional 的线索,这将从资源中调用。有人可以帮忙吗?谢谢。

【问题讨论】:

    标签: java spring spring-boot spring-annotations


    【解决方案1】:

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

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

    Spring @Transactional on @Bean declaration instead of class Implementation

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2019-06-07
      • 2019-03-08
      • 1970-01-01
      • 2016-01-18
      • 1970-01-01
      • 2012-11-30
      • 2017-04-23
      • 1970-01-01
      相关资源
      最近更新 更多