使用idea创建一个springboot的demo
使用springboot创建一个简单的java工程,连接mysql数据库,实现接口访问获取后端返回数据。
idea新建工程
-
1、在idea中选择【File-New-Project】打开新建工程窗口,选择【Spring Initializr】,jdk版本选择1.8
-
2、因为是个demo,所以打包方式选择默认即可,工程使用maven管理。
-
3、选择需要的依赖
-
4、点击next后,点击finish,开始创建工程。
-
5、maven会根据配置拉取相关依赖,等待maven进度条走完,工程则创建完毕。
-
6、右键run启动类【DemoApplication】,会报数据库无法连接的错误,可在启动类注解中设置【exclude = {DataSourceAutoConfiguration.class}】,要求工程启动时不检查数据库连接。
WARN 19720 --- [ restartedMain] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inMemoryDatabaseShutdownExecutor' defined in class path resource [org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.class]: Unsatisfied dependency expressed through method 'inMemoryDatabaseShutdownExecutor' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 7、右键run启动类【DemoApplication】,启动成功。
修改目录结构
-
1、添加如下目录:
controllor:用于对web前端提供访问接口
dao:用于处理数据库相关的操作
entity:用于存放实体类
service:用于编写处理业务的类
-
2、在entity包中创建类Response,该类用做服务端向web前端响应的载体,@Data注解是使用lombok,可以省略setter、getter方法,使代码看着简洁。如果没有setter、getter方法,请求接口时会报错误【No converter found for return value of type: class Response】(需要安装lombok插件)
@Data
public class Response<T> {
private int code;
private String message;
private T data;
public Response(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
}
- 3、在controllor包中创建测试类TestControllor,使用注解RestControllor(可查询下RestControllor和Controllor的区别)
@RestController
public class TestControllor {
@GetMapping("/get")
public Response<String> get() {
return new Response<>(200, "成功", "hello world");
}
}
- 4、重启工程DemoApplication,访问地址:http://localhost:8080/get,可显示请求结果。