前言
Spring进入到4的纪元之后,我想我们大家印象最为深刻的就是Spring-Boot的出现了。今天,我们就来对比下Spring4和Spring3对于restful的支持。
对比
对于Spring3而言,想要实现restful格式的接口有两种方式:第一种的话就是得到response的输出流,写到resPonse的body中去,当然,这种方式一定要注意的是编码格式。下面给个代码示例:
response.setCharacterEncoding(DEFAULT_CHARSET);
response.setHeader(DEFAULT_CONTENT_TYPE_NAME, DEFAULT_CONTENT_TYPE_VALUE);
PrintWriter pw =
null;
try {
pw = response.getWriter();
pw.print(result);
}
catch (Exception e) {
}
finally {
if (pw !=
null)
pw.flush();
pw.close();
}
第二种的话就是在你的方法头部加上ResponseBody注解。当然,这个注解只是让你省掉了那部分转换为json的代码而已。Spring3默认采用的是Jackson来做这样的转换。实际上,我们也可以自定义或者采用fastJson的一个实现来做这样的转换。如下给出代码示例:
@RequestMapping(value =
"/getConfig")
@ResponseBody
public ServiceConfig
getConfig(Integer id) {
return new ServiceConfig();
}
好了,看完了Spring3来看看Spring4里面对于restful的支持。Spring4中只需要一个注解,而且这个注解也足够的见名知意。那就是@RestController。代码示例如下:
@Slf4j
@RestController
public class GreetingController {
@Autowired
TeseService teseService;
private static final String template =
"Hello, %s!";
private final AtomicLong counter =
new AtomicLong();
/**
* @param name
* @return {@link Greeting}
* @ApiOperation annotation you can specify things like the default
* status
* code and the response type being returned when the
* operation completes successfully and also provide
* documentation for other responses than the regular HTTP 200
* OK.
*/
@Autowired
TaoKeDao taoKeDao;
@ApiOperation(value =
"greeting", nickname =
"greeting", response = Greeting.class)
@ApiResponses({
@ApiResponse(code =
404, message =
"Not found", response = Exception.class),
@ApiResponse(code =
200, message =
"Request Successful", response = Greeting.class)})
@RequestMapping(value =
"/greeting", method = RequestMethod.GET, produces =
"application/json")
public List<TagInfo>
greeting(
@
RequestParam(value =
"name", defaultValue =
"World") String name, Greeting greeting) {
log.info(
"qingqiu in");
return teseService.test();
}
}
这里就省掉了@ResponseBody注解。当然,难道只有这些! nono no,实际上Spring-Boot才真的是Spring对于restful接口的支持的最大改变。我们都知道,开始的时候大家使用Spring-MVC来做restful格式接口的书写,但是那时候的MVC依旧支持视图展现啊!也就是说,我们不过是把人家的view那一层忽略而已。 但是SPring-Boot做出的一个改变就是去掉了视图展现,内置tomcat,关于内置的tomcat的各项属相直接就放到一个配置文件中。甚至于,数据源也可以在你那里配置。可以迅速的写一个restful的接口出来。简直妙!当然,毋庸置疑,这两者都有着各自的优点,下面就让阿福来总结一下!
总结
事实上,Spring3的技术成熟度已经很高,而SpringBoot的话目前来说就稍微比较新。但是Spring4的零xml的配置,也就是可以让大家快速的搭建项目原型,开始写业务代码!两者各有优点!看大家的侧重点在哪里呢?如果想要稳定,那最好Spring3.当然,如果想做一个阶段性的实验成果,那就选用Spring-Boot吧!让写代码的速度飞起来!
转载请注明原文地址: https://ju.6miu.com/read-600261.html