用户可以写下一个 url,然后,根据 url 的模式,我的界面应该使用正确的实现。因此,想要根据控制器接收到的 url 动态更改 Spring 的 bean 逻辑执行。
这是我的控制器:
@PostMapping(value = "/url",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.TEXT_HTML_VALUE)
public ResponseEntity<InputStreamResource> parseUrl(@RequestParam String url) throws IOException {
myInterface.dosomething(url);
return ResponseEntity.ok();
}
我的界面:
public interface Myterface {
void myInterface(String url);
}
和我的实现:
@Service
public class myImpl1 implements myInterface {
@Override
public void doSomething(String url) {}
}
我已经尝试过@Qualifier,但它不是动态的。问题是我将有很多不同的 url 模式,因此实现加班,我希望每个模式只添加一个类,而不必修改任何内容。
答案 0 :(得分:1)
您可以在配置类中尝试类似的操作,也可以使用 @Profile
注释:
@Configuration
public class MyConfig {
@Bean
public MyInterface createBean(String URL) {
MyInterface bean;
switch(URL) {
case url1:
bean = new Implementation1();
break;
case url2:
bean = new Implementation2();
break;
default: bean = new DefaultImplementation();
}
return bean;
}
}
查看此 answer 了解更多详情。