小编Mar*_*eti的帖子

Spring:如何在运行时更改接口实现

作为Java开发人员,我经常需要在接口的不同实现之间进行选择.有时候这个选择可以做一次,而有些时候我需要不同的实现来响应我的程序收到的不同输入.换句话说,我需要能够在运行时更改实现.这可以通过一个帮助对象轻松实现,该对象将一些键(基于用户输入)转换为对合适的接口实现的引用.

使用Spring,我可以将这样的对象设计为bean,并将其注入到我需要的任何位置:

public class MyClass {

    @Autowired
    private MyHelper helper;

    public void someMethod(String someKey) {
        AnInterface i = helper.giveMeTheRightImplementation(someKey);
        i.doYourjob();
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,我该如何实现帮助?让我们从这开始:

@Service
public class MyHelper {

    public AnInterface giveMeTheRightImplementation(String key) {
        if (key.equals("foo")) return new Foo();
        else if (key.equals("bar")) return new Bar();
        else ...
    }

}
Run Code Online (Sandbox Code Playgroud)

这种解决方案有几个缺陷.最糟糕的情况之一是从帮助程序返回的实例对于容器是未知的,因此不能从依赖注入中受益.换句话说,即使我Foo像这样定义类:

@Service
public class Foo {

    @Autowired
    private VeryCoolService coolService;

    ...

}
Run Code Online (Sandbox Code Playgroud)

... Foo返回的实例MyHelper不会coolService正确初始化该字段.

为避免这种情况,经常建议的解决方法是在帮助程序中注入每个可能的实现:

@Service
public class MyHelper …
Run Code Online (Sandbox Code Playgroud)

java polymorphism spring dependency-injection interface

5
推荐指数
2
解决办法
2784
查看次数