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. 不建议使用字段注入. 但这个写法很省事, Spring中为什么不建议使用字段注入 - EchoLv - 博客园 (cnblogs.com)
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>aliyun</id> <name>aliyun Maven</name> <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.
Eclipse 快速找到类对应的包名, 要点[Link with Editor]
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"; ResponseEntity<String> response = 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<String, String> requestBody = new HashMap<String,String>(); requestBody.put("id", "9999"); requestBody.put("userName", "123"); requestBody.put("password", "123456"); requestBody.put("sex", "1"); HttpEntity<Map<String, String>> requestEntity = new HttpEntity<Map<String, String>>(requestBody, headers); ResponseEntity<String> response= template.postForEntity(url, requestEntity,String.class); HttpStatus statusCode = response.getStatusCode(); assertThat(statusCode).isEqualTo(HttpStatus.OK); int postCnt =GetAllUser(); assertThat(postCnt).isEqualTo(prevCnt+1); //更新内容 url = "/api/user/9999"; requestBody.put("userName", "JUnit"); requestEntity = new HttpEntity<Map<String, String>>(requestBody, headers); response=template.exchange(url,HttpMethod.PUT,requestEntity,String.class); statusCode = response.getStatusCode(); assertThat(statusCode).isEqualTo(HttpStatus.OK); //https://blog.csdn.net/justin_bob/article/details/103019115 //删除内容 url = "/api/user/9999"; response=template.exchange(url,HttpMethod.DELETE,requestEntity,String.class); //template.delete("api/user/9999"); statusCode = response.getStatusCode(); assertThat(statusCode).isEqualTo(HttpStatus.OK); } }
连接别的机器上的kafka,出现下面错误
Connection to node 1 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
但application.yml配置的不是本地127.0.0.1地址, 这个就要改kafka的 advertised.listeners
# 允许外部端口连接 listeners=PLAINTEXT://0.0.0.0:9092 # 外部代理地址 advertised.listeners=PLAINTEXT://121.201.64.12:9092
Kafka连接服务器出现:Connection to node 1 (localhost/127.0.0.1:9092) could not be established
SLF4J 多个Binding如何处理?
SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/C:/Users/user/.m2/repository/ch/qos/logback/logback-classic/1.2.11/logback-classic-1.2.11.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/C:/Users/user/.m2/repository/org/slf4j/slf4j-reload4j/1.7.36/slf4j-reload4j-1.7.36.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
某个项目假如要去掉kafka send/listen的功能,又暂时保留文件,可以用排除功能,把kafka开头的文件都排除在编译之外
Q: 没有为模块main指定输出路径
A:
Q: 管理依赖库升级
A:
SpringBoot程序如何打包JAR 部署到服务器, 选择【build】,选择【build artifacts】,add JAR from modules with dependcies
重点来了,如果后期POM里增加了依赖库,这个步骤要重做一次,不然虽然能编译,但运行时就会出现
运行时找不到java.lang.NoClassDefFoundError: org/codehaus/janino/ExpressionEvaluator
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)