1. gradle 文件
apply plugin: 'java' apply plugin: 'war' //用于打war包 jar { baseName = 'gs-rest-service' version = '0.1.0' } repositories { mavenCentral() // maven { url "http://repo.spring.io/release" } } sourceCompatibility = 1.7 targetCompatibility = 1.7 dependencies { // compile("org.springframework.boot:spring-boot-starter-web") // testCompile('org.springframework.boot:spring-boot-starter-test') // testCompile('com.jayway.jsonpath:json-path') compile("org.springframework:spring-context:4.3.6.RELEASE") compile("org.springframework:spring-web:4.3.6.RELEASE") compile("org.apache.tomcat:tomcat-servlet-api:8.0.24") compile("org.springframework:spring-web:4.3.6.RELEASE") compile("org.springframework:spring-webmvc:4.3.6.RELEASE") compile("com.fasterxml.jackson.core:jackson-databind:2.8.6") compile("com.fasterxml.jackson.core:jackson-annotations:2.8.6") compile("com.fasterxml.jackson.core:jackson-core:2.8.6") // testCompile('org.springframework.boot:spring-boot-starter-test') testCompile("org.springframework:spring-test:4.3.6.RELEASE") //compile("org.springframework:spring-context:5.0.0.M1") }
服务启动初始化:MyWebApplicationInitializer
package hello; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }web配置:WebConfig/**
*用于加载注解标识的类,如controller,否则无法实例化注解的bean,导致问题出现,如请求无法映射到controller
**/
@Configuration @EnableWebMvc@ComponentScan(basePackages = {"hello"}) public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.enableContentNegotiation(new MappingJackson2JsonView()); registry.jsp(); } }控制器 GreetingController实体对象 Greetingpackage hello; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } }
package hello; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
/**
*用于加载注解标识的类,如controller,否则无法实例化注解的bean,导致问题出现,如请求无法映射到controller
**/