Spring Boot FAQ
eclipse 在marketPlace安装lombok, springtool4, dbeaver,docker tooling
1. tomcat的端口,数据连接这些都存在resourcces/application.yml里
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
server: port: 8082 spring: datasource: driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3307/test?useSSL=false&useUnicode=true&characterEncoding=utf8 username: root password: root
2. 自动导入 点击File—>Settings .Editor—>General—>Auto Import IDEA默认自动导入的快捷键是:Alt+Enter
3. 未配置 SQL 方言。 idea->File->Settings->Languages & Frameworks->SQL Dialects
4. 不建议使用字段注入. 但这个写法很省事,
5. @SpringBootApplication 是一个配置类,它会自动扫描所有Spring Bean( 由Spring框架IOC创建的对象),
SpringBootApplication is a configuration class. It then begins autoscanning all the classes on the Java classpath for other Spring beans.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); //返回一个Spring ApplicationContext 对象。
}
}
A Spring bean is an object that the Spring framework manages at run time with the Inversion of Control (IoC) container.
These are created and added to a “repository of objects” so you can get them later.
只有在容器中的组件,才会拥有 SpringBoot 提供的强大功能。首先就要保证该对 JavaBean 对象在 IoC 容器中,所以需要用到 @Component 注解来添加组件到容器中。
Spring容器来说,当我们把一个Bean标记为@Component后,它就会自动为我们创建一个单例(Singleton)
还有一种Bean,我们每次调用getBean(Class),容器都返回一个新的实例,这种Bean称为Prototype(原型),它的生命周期显然和Singleton不同。声明一个Prototype的Bean时,需要添加一个额外的@Scope注解:
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ConfigurationProperties(prefix = "person") 从yml文件读取时间,会默认yml文件的时间是加了时区的, 当你打印出来默认会改成GMT时间
yml文件 person: lastName: 张三 age: 18 boss: false birth: 1990/12/12 maps: { k1: v1,k2: 12 } lists: ‐ lisi ‐ zhaoliu dog: name: 迪迪 age: 5
在网页JSON输出
{"lastName":"张三","age":18,"boss":false,"birth":"1990-12-11T16:00:00.000+0000","maps":{"k1":"v1","k2":12},"lists":["‐ lisi ‐ zhaoliu"],"dog":{"name":"迪迪","age":"5"}}
6. eclipse的自动完成的快捷键是 输入字母后按"ALT"+'/'
7. 切换配置文件 添加 4 个配置文件:application.yml:默认配置
- application-dev.yml:开发环境配置
- application-test.yml:测试环境配置
- application-prod.yml:生产环境配置
在application.yml加上下面这段,切换到prod环境 Log会显示 c.f.helloworld.HelloworldApplication : The following profiles are active: prod
spring:
#切换配置
profiles:
active: prod #激活开发环境配置
Maven 打包成jar包后(Maven Clean,Maven install),可以用命令行参数--spring.profiles.active=dev 来指定版本
C:\\spring-boot-study-helloworld\target>java -jar helloworld-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
打包生成2个文件
.jar.original 是普通jar包,不包含依赖
.jar 是可执行jar包,包含了pom中的所有依赖,可以直接用java -jar 命令执行
如果是部署,就用.jar
如果是给别的项目用,就要给.jar.original这个包
8. maven 安装dockerfile-maven-plugin ,可以指定image的名字,tag, 直接打包成docker Image, 根目录有Dockerfile和docker-compose.yml, maven build就能自动打包并上传到dockerHub(前提是你注册登录了账号)
docker run -p 8080:8080 ostock/licensing-service:0.0.1-SNAPSHOT
9. 强大的lombok注解@Getter @Setter @ToString
10. Maven的仓库地址是。http://mvnrepository.com/ 比如我们要安装某个jar包, 到这个网址查找,它有一段dependency的代码,复制到POM.xml里就可以了, 参考
Maven 下载地址要改成阿里云的, 在这个目录新建一个文件 c:\users\[用户名]\..m2\setting.xml ,写如下的内容. 不然下载太慢了.我update一下要半个小时
<?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <pluginGroups> pluginGroups> <proxies> proxies> <servers> servers> <mirrors> <mirror> <id>aliyunid> <name>aliyun Mavenname> <mirrorOf>*mirrorOf> <url>https://maven.aliyun.com/repository/public/url> mirror> mirrors> <profiles> profiles> <activeProfiles> activeProfiles> settings>
@PostMapping() 注解这样写,会出现 405错误 方法不被允许 (Method not allowed)
要写成@PostMapping, 或者@PostMapping("xxxxx")
@RequestBody最多只能有一个,而@RequestParam()可以有多个。
前端传递如果是 json 格式的数据,不是Form, 我们要传入的参数是一个对象,那就必须使用 @RequestBody。
- In Spring MVC, "request parameters" map to query parameters, form data, and parts in multipart requests. This is because the Servlet API combines query parameters and form data into a single map called "parameters", and that includes automatic parsing of the request body.
Java String转Date new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2019-01-03 10:59:27")
CRUD RESTful 测试
package com.example.springdemo; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import com.example.springdemo.model.User; @SpringBootTest(classes = DemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserControllerTest { @Autowired private TestRestTemplate template; private final Logger logger = LoggerFactory.getLogger(UserControllerTest.class); private int GetAllUser() throws Exception { String url ="/api/user/users"; ResponseEntityresponse = template.getForEntity(url, String.class); HttpStatus statusCode = response.getStatusCode(); assertThat(statusCode).isEqualTo(HttpStatus.OK); JSONArray users = new JSONArray(response.getBody()); int prevCnt = users.length(); logger.info(users.length()+" user records"); return prevCnt; } @Test public void CRUD_ok() throws Exception { //先查原来有多少个记录 int prevCnt =GetAllUser(); assertThat(prevCnt).isGreaterThanOrEqualTo(1); //增加一个 String url = "/api/user/"; HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.APPLICATION_JSON; headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); // Object user = new User(9999,"JUnit Test","123456",new SimpleDateFormat("yyyy-MM-dd").parse("2022-2-1"),1); Map requestBody = new HashMap (); requestBody.put("id", "9999"); requestBody.put("userName", "123"); requestBody.put("password", "123456"); requestBody.put("sex", "1"); HttpEntity