组件自动装配

  • 激活: @EnableAutoConfiguration
  • 配置:/META-INF/spring.factories //工厂机制
  • 实现:XXXAutoConfiguration

跨域问题

当前端vue使用axios进行跨域访问时,出现

No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://xxx.com‘ is therefore not allowed access.

解决方案:如果 server 端是自己开发的,那么修改相关代码支持跨域即可。如果不是自己开发的,那么可以自己写个后端转发该请求,用代理的方式实现。

在server端

​ SpringBoot增加CorsConfig和CorsFilter两个文件

注意:有些浏览器不允许从HTTPS的域跨域访问HTTP,比如Chrome和Firefox,这些浏览器在请求还未发出的时候就会拦截请求,这是一个特例。

具体内容:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

CorsFilter如果出现以下报错:

1
2
3
4
5
6
7
Description:

The bean 'corsFilter', defined in class path resource [cn/ac/ict/jhzxxmgl/common/config/CorsConfig.class], could not be registered. A bean with that name has already been defined in file [/Users/oven/工作/IdeaProjects/AC_JHZXXMGL_MAN_V2.0/target/classes/cn/ac/ict/jhzxxmgl/filter/CorsFilter.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

原因:filter名字重复

解决办法:在springboot文件加入

main:allow-bean-definition-overriding: true

1
2
3
4
5
6
7
spring:
# 运行环境 dev:开发环境|test:测试环境|prod:生产环境
profiles:
active: dev
main:
#当遇到同样名字的时候,是否允许覆盖注册
allow-bean-definition-overriding: true

JackSon序列化和反序列化

  • 在实体类中要是不想一个属性被序列化,就在这个属性上方添加@JsonIgnore
  • 如果想让这个属性可以被反序列化但是不允许序列化就需要在gettersetter上使用@JsonIgnore@JsonProperty,具体代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 当前页码
*/
@NotNull(message = "当前页码不能为空!")
private int pageNum;

/**
* 页面容量
*/
@NotNull(message = "页面容量不能为空!")
private int pageSize;

//忽略对象转json
@JsonIgnore
public int getPageNum() {
return pageNum;
}

//允许json转对象
@JsonProperty
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}

//忽略对象转json
@JsonIgnore
public int getPageSize() {
return pageSize;
}

//允许json转对象
@JsonProperty
public void setPageSize(int pageSize) {
this.pageSize = pageSize;

获取配置文件

  • 如果要想把配置文件放到jar包外面,使用System.getProperty(“user.dir”)的方式获取

  • 如果想把配置文件打包到jar里面,使用 XXX.class.getClassLoader().getResourceAsStream(propertiesName)的方式获取配置文件