我想在我的项目中使用预先配置好的 Jackson ObjectMapper
(忽略空值和下划线命名法,并使用一些自定义模块)。
在我的大型项目中,我无法使Spring MVC实际使用此映射器。
build.gradle文件:
buildscript {
ext {
springBootVersion = '1.5.6.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.boot:spring-boot-starter-jetty:${springBootVersion}")
compile("org.springframework.boot:spring-boot-starter-web:${springBootVersion}")
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.8'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.8'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
我的application.yml文件:
spring:
application:
name: Jackson test
jackson:
property-naming-strategy: SNAKE_CASE
default-property-inclusion: non_empty
debug: true
一个容器类:
public class MyLocationEntity {
public String nameAndSnake;
}
A config class:
@Configuration
@EnableWebMvc
public class AppConfig {
}
还需要一个控制器:
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private ObjectMapper objectMapper;
@RequestMapping(value = "/test", produces = "application/json")
public MyLocationEntity test() throws JsonProcessingException {
MyLocationEntity location = new MyLocationEntity();
location.nameAndSnake = "hello world";
String expexted = objectMapper.writeValueAsString(location);
return location;
}
}
如果我现在在调试器中查看expected
的值,它是{"name_and_snake":"hello world"}
。
但是如果我让控制器运行,实际响应是{"nameAndSnake":"hello world"}
。
当我删除@EnableWebMvc
时,它可以正常工作。如何在使用配置的映射器与MVC并不删除Web MVC的其余自动配置?
@EnableWebMvc
,我会禁用自动配置,因此在application.yml中进行的配置不会生效。 <-- 这将是一个答案,而不是“你为什么要使用它”的问题。 - Tom