java - 调用服务依赖于使用单个控制器的 PathVariable
问题描述
我需要从单个控制器调用实现服务取决于 PathVariable
/{variable}/doSomething
public void controller(@PathVariable("variable") variable)
if variable == 1
call service1Impl();
else if variable == 2
call service2Impl();
但我需要我的控制器像这样,而不是使用 if,否则
public void controller(...) {
call service();
}
在获取任何 PathVariable 时,我需要找到一些自动配置我的应用程序的解决方案,它应该知道需要调用哪个服务。
我尝试使用
加载 Config.class 作为上下文 - @Configuration
@Configuration public class AppConfig { @Bean(name = "variableValue1") public DummyService getService1() { return new DummyServiceImpl(); } @Bean(name = "variableValue2") public AnotherService getService2() { return new AnotherServiceImpl(); }
但是在控制器中我需要将此配置加载为上下文,然后它不够简单
豆厂
它的工作,但我的控制器对我来说不够简单
我需要这样做,但它必须基于 PathVariable 而不是属性名称。
@Configuration
public class GreetingServiceConfig {
@Bean
@ConditionalOnProperty(name = "language.name", havingValue = "english", matchIfMissing = true)
public GreetingService englishGreetingService() {
return new EnglishGreetingService();
}
@Bean
@ConditionalOnProperty(name = "language.name", havingValue = "french")
public GreetingService frenchGreetingService() {
return new FrenchGreetingService();
}
}
------------------------------------------------
@RestController
public class HomeController {
@Autowired
GreetingService greetingService;
@RequestMapping("/")
public String home() {
return greetingService.greet();
}
}
解决方案
所以基于pathvariable,需要执行具体的方法..
这只是一个建议,因为您不想选择 if else
你可以为此使用Hashmap,
HashMap<Integer, Runnable> hm = new HashMap<Integer, Runnable> ();
例如,
pathvariable 是 1 -> 执行的方法是 method1()
路径变量是 2 -> 执行的方法是 method2()
hm.put(1, method1())
hm.put(2, method2())
所以在控制器中,
如果 PathVariable 为 1,
hm.get(1).run(); // hm.get(variable).run()