【问题标题】:Getting Bean instance as null using Strategy Design Pattern and @Autowired使用策略设计模式和@Autowired 将 Bean 实例设为 null
【发布时间】:2021-08-15 17:25:52
【问题描述】:

您好,我正在尝试使用策略设计模式。我在 TestServiceImpl 类中将 ReEncryptionOperation bean 设为 null。

这是我的界面

public interface ReEncryptionOperation {

    void performOperation (String name);
}

这些是我的实现类

public class Test1 implements ReEncryptionOperation {


@Override
public void performOperation(String name){

    return ....;
   }
}


public class Test2 implements ReEncryptionOperation {


@Override
public void performOperation(String name) {

    return ....;
}
}

这是我定义为 bean 的配置类

  @Configuration
  @Slf4j
  public class TestConfiguration
  {
   @Bean("reEncryptionOperation")
  public ReEncryptionOperation getReEncryptionOperation () throws ReEncryptionException {

    if (annotationSupport) {
        return new Test1();
    }
    return new Test2();
}

 }

这是我的服务类,我正在尝试使用 @Autowired 使用 ReEncryptionOperation。但我得到了空值。

 @Component
@Slf4j
 public class TestServiceImpl
 {

@Autowired
private ReEncryptionOperation reEncryptionOperation;



public ReEncryptionResponse submitJob (
    final ReEncryptionRequest reEncryptionRequest) throws ReEncryptionException
{
        reEncryptionOperation.performOperation(test);
        
}

}

【问题讨论】:

    标签: java inversion-of-control autowired strategy-pattern


    【解决方案1】:

    您的配置似乎没问题。 检查 TestConfiguration 是否位于 spring 扫描的包中。

    为确保您的 bean 是在运行时创建的,请在方法 getReEncryptionOperation 中放置一个断点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多