我目前正在关注有关Spring MVC和REST服务的tutorial。这是一个简单的hello world项目。
我不明白。在pom.xml中我们设置了jackson依赖,但它永远不会被配置。 Spring如何知道如何使用json对象?
以下是代码示例:
pom xml(依赖项):
if let num = defaults.string(forKey: "number") {
lab.text = num
}
AppConfiguration:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
</dependencies>
AppInitializer:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "package.to.scan")
public class AppConfiguration {
}
AppController:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
型号:
@RestController
public class AppController {
@RequestMapping("/")
public String welcome() {
return "Welcome to RestTemplate Example.";
}
@RequestMapping("/hello/{player}")
public Message message(@PathVariable String player) {
Message msg = new Message(player, "Hello " + player);
return msg;
}
}
答案 0 :(得分:1)
Spring有一组默认的HttpMessageConverter
s,其中一个是MappingJackson2HttpMessageConverter
,如果内容类型是json并且Jackson在类路径中可用,则使用它。