无法弄清楚如何在策略模式设计中进行依赖注入或自动装配

Unable to figure out how to do Dependency Injection or Auto-wiring in a Strategy Pattern design

我已经实现了一个策略模式,我期待使用 Spring 的依赖注入。

我有以下用例:

class Controller {
    @Autowired
    private Interface behaviour ;
    private String someData;
    // getters setters 

    public void doBehaviour(){
        this.behaviour.doBehaviour(someData); // getting null pointer here
    }
}

public Interface IBehaviour {
    void doBehaviour(String someData);
}
@Component
class MyCustomBehaviour1 implements IBehaviour {



    @Override
    void doBehaviour(String ){
        System.out.println("Playing with MyCustomBehaviour1 -> " + someData);
    }

}

My Main class -

public Main {
    AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    Controller ctrln = new Controller();
    ctrln.setBehaviour(); 
    ctrln.doBehaviour(); 
}

在这种情况下我怎样才能有效地进行自动装配/依赖注入或者我怎样才能改进这段代码?我是 Spring 的新手,因此无法弄清楚自动装配部分,因为接口实现和控制器之间存在关联 class

Edit : Removed circular association

它在从 spring bean 循环中获取 Controller 对象后工作,而不是创建我们自己的对象。

首先你应该在这里删除循环依赖。 一个建议是从 Controller class 中删除 private Interface behaviour ; 并在 Controller class 之外的某个地方调用 doBehaviour

完成后,您就可以进入自动装配。基本是为了自动装配,spring 上下文需要一个特定 class 类型的 bean。根据您的 class 有几种方法可以做到这一点,您可以只输入

@Component
class Controller {

@组件注释。

Note : In your application class There should be a @ComponentScan("relevant.package") indicating spring context to where to find your beans.

一旦你创建了你的 bean,你就可以按如下方式自动装配它,

@Component
class MyCustomBehaviour1 implements IBehaviour {

// instance of controller 
private Controller cntrlInstanceToUseData;

@Autowired
public MyCustomBehaviour (Controller ctrlInst){
    this.cntrlInstanceToUseData = ctrlInst;
}

@Override
void doBehaviour(){
    System.out.println("Playing with MyCustomBehaviour1 -> " + cntrlInstanceToUseData.getSommeData());
}
}

现在您真的不需要创建 Controller 对象和 Behavior 对象,访问 doBehaviour 应该通过使用

在任何您想要的地方完成
@Autowire
private IBehaviour myBehaviour

更多信息请read