在spring-boot中,引入非常多的新特性,简化了spring中繁琐,臃肿的开发方式
组合注解
使用组合注解,通过其名称,就可以非常容易知道其意义,提高代码的可读性
@RestController=@Controller+@ResponseBody
@GetMapping=@RequestMapping(method = RequestMethod.GET)
http客户端
spring-boot提供了专门用于restApi调用的模板类RestTemplate,该模板类使用了单例的设计模式,底层也实现了线程池,http长连接的特性,开发人员非常方便就可以开发出高性能的http客户端程序
列子
spring-cloud-consumer-user工程
UserController.java
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.example.demo.model.User;
@RestController
@RequestMapping(value="/user")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@GetMapping(value="/get/{id}")
public User get(@PathVariable String id){
return restTemplate.getForObject("http://localhost:8080/user/get?id="+id, User.class);
}
}
CoreConfig.java
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class CoreConfig {
@Bean
public RestTemplate restTemplateBean(){
return new RestTemplate();
}
}
User.java
package com.example.demo.model;
import java.util.Date;
public class User {
private String id;
private String userName;
private int age;
private Date birthday;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
application.properties
server.port=8081
spring-cloud-provider工程
UserController.java
package com.dennis.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.dennis.model.User;
@RestController
@RequestMapping(value="/user")
public class UserController {
private Map<String, User> umap = new HashMap();
public UserController(){
umap.put("1", new User("1", "xiaoming", 30));
umap.put("2", new User("2", "xiaohong", 20));
umap.put("3", new User("3", "zhangsan", 80));
umap.put("4", new User("4", "lisi", 10));
umap.put("5", new User("5", "wangwu", 22));
}
@GetMapping(value="/get")
@ResponseBody
public User get(String id){
return umap.get(id);
}
}