第一个spring-boot工程

1.登陆网址https://start.spring.io/ 创建一个简单的spring-boot工程,这时会生成一个zip压缩文件

 2.解压生成的压缩文件spring-boot.zip,解压后导入到eclipse中

3.pom文件引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.szcatic</groupId>
	<artifactId>spring-boot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>spring-boot</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</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-starter-web</artifactId>
	 	</dependency>
		<dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-devtools</artifactId>
	        <optional>true</optional>
   		</dependency>
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-webmvc</artifactId>
		</dependency>
		<!-- junit5运行所需jar包 -->
		<dependency>
		    <groupId>org.junit.jupiter</groupId>
		    <artifactId>junit-jupiter-engine</artifactId>
		    <scope>test</scope>
		</dependency>
		<dependency>
		    <groupId>org.junit.platform</groupId>
		    <artifactId>junit-platform-runner</artifactId>
		    <scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
                	<fork>true</fork>
            	</configuration>
			</plugin>
		</plugins>
	</build>


</project>

3.创建一个控制器类HelloWorldController

package com.szcatic.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
public class HelloWorldController {
	
	@RequestMapping("/hello")
    public String getHello() {
        return "Hello World";
    }
	
	public static void main(String[] args) {
		SpringApplication.run(HelloWorldController.class, args);
	}
}

 

 5.运行main主程序,控制台显示如下内容,表示启动成功


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-11-14 17:31:00.829  INFO 5612 --- [  restartedMain] c.s.controller.HelloWorldController      : Starting HelloWorldController on zsx with PID 5612 (F:\workspace4.7\spring-boot\target\classes started by admin in F:\workspace4.7\spring-boot)
2018-11-14 17:31:00.837  INFO 5612 --- [  restartedMain] c.s.controller.HelloWorldController      : No active profile set, falling back to default profiles: default
2018-11-14 17:31:00.936  INFO 5612 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2018-11-14 17:31:00.936  INFO 5612 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2018-11-14 17:31:03.767  INFO 5612 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-11-14 17:31:03.823  INFO 5612 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-11-14 17:31:03.823  INFO 5612 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.12
2018-11-14 17:31:03.856  INFO 5612 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : Loaded APR based Apache Tomcat Native library [1.2.16] using APR version [1.6.3].
2018-11-14 17:31:03.857  INFO 5612 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2018-11-14 17:31:03.857  INFO 5612 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2018-11-14 17:31:05.026  INFO 5612 --- [  restartedMain] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.0.2m  2 Nov 2017]
2018-11-14 17:31:05.231  INFO 5612 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-11-14 17:31:05.231  INFO 5612 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 4295 ms
2018-11-14 17:31:05.304  INFO 5612 --- [  restartedMain] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-11-14 17:31:05.310  INFO 5612 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-14 17:31:05.310  INFO 5612 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-14 17:31:05.311  INFO 5612 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
2018-11-14 17:31:05.311  INFO 5612 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-14 17:31:05.647  INFO 5612 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2018-11-14 17:31:06.008  INFO 5612 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2018-11-14 17:31:06.100  INFO 5612 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-14 17:31:06.104  INFO 5612 --- [  restartedMain] c.s.controller.HelloWorldController      : Started HelloWorldController in 5.701 seconds (JVM running for 6.438)

6.打开浏览器,输入localhost:8080和localhost:8080/hello,分别显示如下:

显示以上两个界面,表示spring-boot工程已正常运行

7.编写测试类

package com.szcatic.test.controller;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.szcatic.controller.HelloWorldController;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = HelloWorldController.class)
public class HelloWorldControllerTests {

	private MockMvc mvc;

	@BeforeEach
	void init() throws Exception {
		mvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();
	}

	@Test
	void testGetHello() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
				.andExpect(MockMvcResultMatchers.status().isOk())
				.andExpect(MockMvcResultMatchers.content().string(Matchers.equalTo("Hello World")))
				.andDo(MockMvcResultHandlers.print()).andReturn();
	}
	
	
}

8.运行测试方法testGetHello ,控制台显示如下内容,表示测试正常

17:41:39.500 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
17:41:39.523 [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)]
17:41:39.561 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.szcatic.test.controller.HelloWorldControllerTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
17:41:39.608 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.szcatic.test.controller.HelloWorldControllerTests], using SpringBootContextLoader
17:41:39.611 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.controller.HelloWorldControllerTests]: class path resource [com/szcatic/test/controller/HelloWorldControllerTests-context.xml] does not exist
17:41:39.611 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.controller.HelloWorldControllerTests]: class path resource [com/szcatic/test/controller/HelloWorldControllerTestsContext.groovy] does not exist
17:41:39.612 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.szcatic.test.controller.HelloWorldControllerTests]: no resource found for suffixes {-context.xml, Context.groovy}.
17:41:39.679 [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.szcatic.test.controller.HelloWorldControllerTests]
17:41:39.772 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.szcatic.test.controller.HelloWorldControllerTests]: using defaults.
17:41:39.773 [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]
17:41:39.783 [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]
17:41:39.784 [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]
17:41:39.785 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@5dda768f, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7a8c8dcf, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@24269709, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@2aceadd4, org.springframework.test.context.support.DirtiesContextTestExecutionListener@24aed80c, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@3a52dba3, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@2a5c8d3f, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@752325ad, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@279fedbd, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@b3ca52e]
17:41:39.799 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@d35dea7 testClass = HelloWorldControllerTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@7770f470 testClass = HelloWorldControllerTests, locations = '{}', classes = '{class org.springframework.mock.web.MockServletContext, class org.springframework.mock.web.MockServletContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3b2cf7ab, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@5ad851c9, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4f638935, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@7995092a, org.springframework.test.context.web.socket.MockServerContainerContextCustomizer@70be0a2b], 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].
17:41:39.829 [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.0.RELEASE)

2018-11-14 17:41:40.244  INFO 9508 --- [           main] c.s.t.c.HelloWorldControllerTests        : Starting HelloWorldControllerTests on zsx with PID 9508 (started by admin in F:\workspace4.7\spring-boot)
2018-11-14 17:41:40.246  INFO 9508 --- [           main] c.s.t.c.HelloWorldControllerTests        : No active profile set, falling back to default profiles: default
2018-11-14 17:41:40.573  INFO 9508 --- [           main] c.s.t.c.HelloWorldControllerTests        : Started HelloWorldControllerTests in 0.733 seconds (JVM running for 1.939)
2018-11-14 17:41:41.588  INFO 9508 --- [           main] o.s.mock.web.MockServletContext          : Initializing Spring TestDispatcherServlet ''
2018-11-14 17:41:41.588  INFO 9508 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2018-11-14 17:41:41.590  INFO 9508 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 1 ms

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /hello
       Parameters = {}
          Headers = {Accept=[application/json]}
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.szcatic.controller.HelloWorldController
           Method = public java.lang.String com.szcatic.controller.HelloWorldController.getHello()

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[application/json;charset=ISO-8859-1], Content-Length=[11]}
     Content type = application/json;charset=ISO-8859-1
             Body = Hello World
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

9.目录结构 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值