版权声明:本文为博主原创文章,经博主允许,可自由共享,尽量不要用于商业用途。 https://blog.csdn.net/matrixbbs/article/details/88391905
新建一个Spring Starter Project
项目名:springboot-example-01
STS工具会自动建立和搭架项目框架,引用如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
用maven工具来组织
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
项目截图如下:
新建一个包,包名是testController
然后在该包下创建一个类TestController
代码如下:
package com.zfh.springbootexample01.testController;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zfh.springbootexample01.entity.User;
/**
* 一个handler,也就是一个控制器里的具体的一个一个的处理
* 这个类封装了很多个handler,用@RequestMapping来指定访问的URL
* 但URL的根是"/"
* 这个类,也就是控制器的URL是"/test"
* 具体的handler的URL是"/test/hello"
* @author fhzheng
*
*/
@RestController
@RequestMapping(value = "/test")
public class TestController {
/**
* 用GET请求方式,返回一个串
* @return 一个字符串
*/
@RequestMapping(value = "/hello", method = { RequestMethod.GET })
public String sayHello01() {
return "Hello SpringBoot from fhzheng20190311 RequestMethod.GET";
}
/**
* 用POST请求方式,返回一个串
* @return 一个字符串
*/
@RequestMapping(value = "/hello", method = { RequestMethod.POST })
public String sayHello02() {
return "Hello SpringBoot from fhzheng20190311 RequestMethod.POST";
}
/**
* URL带参数进行请求,返回一个封装结果,即一个Map
* @param 请求中要求有一个参数 name
* @return Map<String, Object>
*/
@RequestMapping(value="/getParams")
public Map<String, Object> getParams(@RequestParam String name) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("defaultName", "zhengfenghua default");
map.put("getName", name);
return map;
}
/**
* 请求一个用户
* @return user
* @throws ParseException
*/
@RequestMapping(value="/getUser")
public User getUser() throws ParseException {
User user = new User();
user.setName("郑丰华");
user.setSex("男");
user.setAge(40);
// SimpleDateFormat sf = new SimpleDateFormat("2019-03-11");
// Date date = sf.parse(null);
user.setBirthday(new Date());
return user;
}
/**
* 请求一组用户
* @return List<User>
*/
@RequestMapping(value="/getUsers")
public List<User> getUsers(){
List<User> users = new ArrayList<User>();
User user1 = new User();
user1.setName("郑丰华");
user1.setSex("男");
user1.setAge(20);
user1.setBirthday(new Date());
User user2 = new User();
user2.setName("郑富华");
user2.setSex("女");
user2.setAge(30);
user2.setBirthday(new Date());
User user3 = new User();
user3.setName("郑生华");
user3.setSex("保密");
user3.setAge(40);
user3.setBirthday(new Date());
users.add(user1);
users.add(user2);
users.add(user3);
return users;
}
}
还需要一个User类,代码如下:
package com.zfh.springbootexample01.entity;
import java.util.Date;
public class User {
private String name;
private String sex;
private Integer age;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
完成后,就可以跑项目了
对于post请求,建议安装一个postman来模拟,即可以进行相应的测试。
完成以后,如果要进行打包,则进行如下操作
然后,操作如下,注意maven的打包参数:clean package
打包日志如下:
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------< com.zfh:springboot-example-01 >--------------------
[INFO] **Building springboot-example-01 0.0.1-SNAPSHOT**
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ springboot-example-01 ---
[INFO] Deleting D:\JavaWork20181\springboot-example-01\target
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ springboot-example-01 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ springboot-example-01 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to D:\JavaWork20181\springboot-example-01\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ springboot-example-01 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory D:\JavaWork20181\springboot-example-01\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ springboot-example-01 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to D:\JavaWork20181\springboot-example-01\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ springboot-example-01 ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] **T E S T S**
[INFO] -------------------------------------------------------
[INFO] Running com.zfh.springbootexample01.SpringbootExample01ApplicationTests
13:08:00.663 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:00.671 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
13:08:00.682 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
13:08:00.712 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
13:08:00.730 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests], using SpringBootContextLoader
13:08:00.736 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]: class path resource [com/zfh/springbootexample01/SpringbootExample01ApplicationTests-context.xml] does not exist
13:08:00.736 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]: class path resource [com/zfh/springbootexample01/SpringbootExample01ApplicationTestsContext.groovy] does not exist
13:08:00.737 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
13:08:00.738 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]: SpringbootExample01ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
13:08:00.830 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:00.989 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [D:\JavaWork20181\springboot-example-01\target\classes\com\zfh\springbootexample01\SpringbootExample01Application.class]
13:08:00.994 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.zfh.springbootexample01.SpringbootExample01Application for test class com.zfh.springbootexample01.SpringbootExample01ApplicationTests
13:08:01.250 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]: using defaults.
13:08:01.252 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
13:08:01.287 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
13:08:01.291 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
13:08:01.294 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5c5eefef, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@16293aa2, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@5158b42f, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@595b007d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@72d1ad2e, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@2d7275fc, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@399f45b1, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@38c6f217, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@478190fc, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@79e2c065]
13:08:01.304 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.306 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.311 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.312 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.315 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.316 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.333 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@67c27493 testClass = SpringbootExample01ApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1a482e36 testClass = SpringbootExample01ApplicationTests, locations = '{}', classes = '{class com.zfh.springbootexample01.SpringbootExample01Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@13c27452, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5ed828d, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@2db7a79b, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@c81cdd1], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
13:08:01.338 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.338 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.zfh.springbootexample01.SpringbootExample01ApplicationTests]
13:08:01.382 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.3.RELEASE)
2019-03-11 13:08:01.886 INFO 212 --- [ main] .z.s.SpringbootExample01ApplicationTests : Starting SpringbootExample01ApplicationTests on JSZX-ZFH with PID 212 (started by fhzheng in D:\JavaWork20181\springboot-example-01)
2019-03-11 13:08:01.888 INFO 212 --- [ main] .z.s.SpringbootExample01ApplicationTests : No active profile set, falling back to default profiles: default
2019-03-11 13:08:04.623 INFO 212 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-03-11 13:08:05.041 INFO 212 --- [ main] .z.s.SpringbootExample01ApplicationTests : Started SpringbootExample01ApplicationTests in 3.645 seconds (JVM running for 5.087)
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.927 s - in com.zfh.springbootexample01.SpringbootExample01ApplicationTests
2019-03-11 13:08:05.395 INFO 212 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
[INFO]
[INFO] Results:
[INFO]
**[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0**
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:3.1.1:jar (default-jar) @ springboot-example-01 ---
[INFO] Building jar: D:\JavaWork20181\springboot-example-01\target\springboot-example-01-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.1.3.RELEASE:repackage (repackage) @ springboot-example-01 ---
[INFO] Replacing main artifact with repackaged archive
[INFO] ------------------------------------------------------------------------
**[INFO] BUILD SUCCESS**
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18.455 s
[INFO] Finished at: 2019-03-11T13:08:08+08:00
[INFO] ------------------------------------------------------------------------
[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.
最后,在控制台运行该包的命令是:
java -jar springboot-example-01-0.0.1-SNAPSHOT.jar