如何在JavaSpring中基于外部配置将接口绑定到特定的实现?
我想在程序启动时从json配置文件中读取是使用Mongo db后端还是postgres后端。基于此配置,我想将相应的服务注入控制器 我有以下界面:如何在JavaSpring中基于外部配置将接口绑定到特定的实现?,java,spring,dependency-injection,inversion-of-control,Java,Spring,Dependency Injection,Inversion Of Control,我想在程序启动时从json配置文件中读取是使用Mongo db后端还是postgres后端。基于此配置,我想将相应的服务注入控制器 我有以下界面: public interface IItemsService { public void putItem(); } 以及实现它的两个类: public class MongoItemsService implements IItemsService { private SomeMongoConnection conn;
public interface IItemsService {
public void putItem();
}
以及实现它的两个类:
public class MongoItemsService implements IItemsService
{
private SomeMongoConnection conn;
public MongoItemsService (SomeMongoConnection conn)
{
this.conn = conn;
}
@Override
public void putItem() {
System.out.println("Mongo");
}
}
及
我终于有了一个我想要注入的控制器:
@RestController
public class ItemsController {
private IItemsService itemsService;
@RequestMapping("/putitem")
public void putItem() {
this.itemsService.putItem();
}
@Autowired
public ItemsController(IItemsService itemsService)
{
this.itemsService = itemsService;
}
}
因此,基于json配置,我想将相应的IItemsService注入控制器的构造函数。我希望避免在单独的接口和实现的服务类上使用注释,因为它们可能用于其他对spring没有严格依赖性的项目中。如何在启动时动态设置接口与具体类的绑定 在xml中使用@primary或primary属性。请参考下面的链接。Spring文档:这不表示某种默认情况吗?在这种情况下,我认为这两种服务都不是默认的/更优惠的。我做了更多的研究,似乎使用配置文件也是一种选择?@user3517454使用配置文件将是这种情况下的最佳解决方案。是的,您可以加载特定于配置文件的bean,但请记住,其他应用程序也需要启用该配置文件。如果只启用主bean,那么如果发现两个相同类型的bean,它将被注入控制器。
@RestController
public class ItemsController {
private IItemsService itemsService;
@RequestMapping("/putitem")
public void putItem() {
this.itemsService.putItem();
}
@Autowired
public ItemsController(IItemsService itemsService)
{
this.itemsService = itemsService;
}
}