![](/img/trans.png)
[英]How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
[英]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.