Spring Boot 搭建简单微服务(REST)
2018-01-31 本文已影响0人
半只温柔
(IDEA),创建maven项目,创建Maven项目对象模型POM
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.rest.test</groupId>
<artifactId>spring-boot</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
</project>
dependencies下的两个依赖,第一个:spring-boot类库,第二个:去除idea自身tomcat容器
然后创建工程:
捕获2.PNG
1:controller,路由管理,可以创建接口,更清晰点
UserController:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/getUser")
public Object getUser() {
Map<String, User> map = new HashMap<String, User>();
map.put("user", userService.getUserById(123));
return map;
}
}
2:dao数据访问层,没有数据库就假数据了
还是 接口+实现类(多态的运用,解耦合):
public interface UserDao {
User getPhotoNameById(int id);
}
@Repository("UserDao")
public class UserDaoImpl implements UserDao {
@Override
public User getPhotoNameById(int id) {
User p = new User();
p.setId(123);
p.setName("浩然真帅");
return p;
}
}
3:entity实体类
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4:service业务层:
public interface UserService {
User getUserById(int id);
}
@Service("UserService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userdao;
@Override
public User getUserById(int id) {
return userdao.getPhotoNameById(id);
}
}
5:Application 微服务的启动:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
6:resource下application.properties
配置端口,因为我的端口8080占用了,也懒得看就配置一下8088
server.port=8088
运行application的main方法:
捕获.PNG
哈哈哈哈,感谢:)