在java-spring网络应用程序中,我希望能够动态注入bean.例如,我有一个具有2种不同实现的接口:
在我的应用程序中,我正在使用一些属性文件来配置注入:
#Determines the interface type the app uses. Possible values: implA, implB
myinterface.type=implA
Run Code Online (Sandbox Code Playgroud)
我的注入实际上有条件地在属性文件中的属性值上加载.例如,在这种情况下myinterface.type = implA,只要我注入MyInterface,将注入的实现将是ImplA(我通过扩展条件注释完成了).
我希望在运行时 - 一旦属性发生更改,将发生以下情况(无需重新启动服务器):
myinterface.type=implBImplB将被注入到使用MyInterface的地方我想要刷新我的上下文,但这会产生问题.我想可能会使用setter进行注入,并在重新配置属性后重新使用这些setter.是否有这种要求的工作实践?
有任何想法吗?
UPDATE
正如一些人所建议我可以使用一个工厂/注册表来保存两个实现(ImplA和ImplB)并通过查询相关属性返回正确的实现.如果我这样做,我还有第二个挑战 - 环境.例如,如果我的注册表看起来像这样:
@Service
public class MyRegistry {
private String configurationValue;
private final MyInterface implA;
private final MyInterface implB;
@Inject
public MyRegistry(Environmant env, MyInterface implA, MyInterface ImplB) {
this.implA = implA;
this.implB = implB;
this.configurationValue = env.getProperty("myinterface.type");
}
public MyInterface getMyInterface() {
switch(configurationValue) {
case "implA":
return implA; …Run Code Online (Sandbox Code Playgroud)