繁体   English   中英

如何在Spring Boot中通过post调用注入依赖项?

[英]How to inject dependencies with post call in spring boot?

我有一个将映射到个人资料的帖子映射。个人资料包含某些要注入依赖项的参数。 对于每个配置文件,我都可以注入完全不同的一组实现。 使用guice,我可以通过在我的配置文件中添加模块属性并在接收配置文件时创建该guice模块来完成此工作,而其他依赖项注入则由guice负责。

public class GuiceModule extends AbstractModule {
public GuiceModule(Profile profile) {
                    super(profile);
                  }
                @Override
                protected void configureModule() { 
                  bind(Bean1.class).toProvider(Bean1Impl.class);
                  bind(Bean2.class).to(Bean2Impl.class);
                  bind(Bean3.class).to(Bean3Impl.class);
                  bind(Bean4.class).to(Bean4Impl.class);
                  bind(Bean5.class).to(Bean5Imple.class);
                  bind(ParentBean.class).to(ParentBeanImpl.class);
              }

              @Override
              public void configure() {
                this.configureModule();
              }   
    }

在我的控制器中

@PostMapping(path = "/profiles/add" , consumes = "application/json")
    void addProfile(@RequestBody Profile profile)
        {
            //with guice 
            Injector injector = Guice.getInjector(Class.forName(profile.getModule));
            injector.getInstance(ParentBean.class).execute();
        }

但是用spring-boot找不到如何实现这一目标。
每当我在帖子调用中收到新的配置文件时, Update可以创建一个新的AnnotationConfigApplicationContext。代码将如下所示。

@PostMapping(path = "/profiles/add" , consumes = "application/json")
void addProfile(@RequestBody Profile profile)
{
    String clazz = profile.getConfigurationClass();
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Class.forName(clazz)); //This will create a new IoC container with its own beans.
    ParentBean bean = context.getBean(ParentBean.class)
    bean.execute()
}

这可以工作,但是我不确定这是否是一个好习惯。

在问题中,不清楚哪个参数决定了服务调用。 假设它是一个枚举,则可以保留一个以枚举为键的映射,并自动将服务自动绑定为一个值。 现在,基于该参数,您可以调用不同的实现。

@PostMapping(path = "/profiles/add" , consumes = "application/json")
void addProfile(@RequestBody Profile profile)
{
 Object service =  this.map.get("your_field");
 service.yourMethod(profile);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM