Spring boot2.0 入门(七)-使用工厂模式响应请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011311291/article/details/84555412

有时候只想随便做个微服务,也并不想使用什么Rest风格,就所有接口都使用一个字段进行标识(例子使用method),然后调用相应的接口方法,以下代码所有的http请求都会进入demo这个方法,然后通过请求带的请求标识,通过Spring IOC容器获取相应的Service Bean(这里为Service中的impl取名xxxxProcessor),然后执行相应的方法,这里所有的Service都继承了BaseInterface接口,实现process方法。

@RestController
@RequestMapping("/test")
public class CommandController implements ApplicationContextAware
{
	private ApplicationContext applicationContext = null;
	
    @Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException 
	{
		this.applicationContext = applicationContext;
	}
    
    @RequestMapping("/test") 
    public testResult demo(@RequestBody Map<String, String> params) 
    {
		BaseInterface processor = (BaseInterface) applicationContext.getBean(params.get("method")+"Processor");
    	return processor.process(params);
    }
}

猜你喜欢

转载自blog.csdn.net/u011311291/article/details/84555412