Quellcode durchsuchen

Update to Spring Boot 1.4 features

Dave Syer vor 8 Jahren
Ursprung
Commit
7381cf1082

+ 5
- 5
README.adoc Datei anzeigen

@@ -73,7 +73,7 @@ include::initial/src/main/java/hello/Application.java[]
73 73
 
74 74
 The `main()` method uses Spring Boot's `SpringApplication.run()` method to launch an application. Did you notice that there wasn't a single line of XML? No **web.xml** file either. This web application is 100% pure Java and you didn't have to deal with configuring any plumbing or infrastructure.
75 75
 
76
-The `run()` method returns an `ApplicationContext` and this application then retrieves all the beans that were created either by your app or were automatically added thanks to Spring Boot. It sorts them and prints them out.
76
+There is also a `CommandLineRunner` method marked as a `@Bean` and this runs on start up. It retrieves all the beans that were created either by your app or were automatically added thanks to Spring Boot. It sorts them and prints them out.
77 77
 
78 78
 == Run the application
79 79
 To run the application, execute:
@@ -165,7 +165,7 @@ Now write a simple unit test that mocks the servlet request and response through
165 165
 include::complete/src/test/java/hello/HelloControllerTest.java[]
166 166
 ----
167 167
 
168
-Note the use of the `MockServletContext` to set up an empty `WebApplicationContext` so the `HelloController` can be created in the `@Before` and passed to `MockMvcBuilders.standaloneSetup()`. An alternative would be to create the full application context using the `Application` class and `@Autowired` the `HelloController` into the test. The `MockMvc` comes from Spring Test and allows you, via a set of convenient builder classes, to send HTTP requests into the `DispatcherServlet` and make assertions about the result.
168
+The `MockMvc` comes from Spring Test and allows you, via a set of convenient builder classes, to send HTTP requests into the `DispatcherServlet` and make assertions about the result. Note the use of the `@AutoConfigureMockMvc` together with `@SpringBootTest` to inject a `MockMvc` instance. Having used `@SpringBootTest` we are asking for the whole application context to be created.  An alternative would be to ask Spring Boot to create only the web layers of the context using the `@WebMvcTest`. Spring Boot automatically tries to locate the main application class of your application in either case, but you can override it, or narrow it down, if you want to build something different.
169 169
 
170 170
 As well as mocking the HTTP request cycle we can also use Spring Boot to write a very simple full-stack integration test. For example, instead of (or as well as) the mock test above we could do this:
171 171
 
@@ -175,7 +175,7 @@ As well as mocking the HTTP request cycle we can also use Spring Boot to write a
175 175
 include::complete/src/test/java/hello/HelloControllerIT.java[]
176 176
 ----
177 177
 
178
-The embedded server is started up on a random port by virtue of the `@IntegrationTest("${server.port=0}")` and the actual port is discovered at runtime with the `@Value("${local.server.port}")`.
178
+The embedded server is started up on a random port by virtue of the `webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT` and the actual port is discovered at runtime with the `@LocalServerPort`.
179 179
 
180 180
 == Add production-grade services
181 181
 If you are building a web site for your business, you probably need to add some management services. Spring Boot provides several out of the box with its http://docs.spring.io/spring-boot/docs/{spring_boot_version}/reference/htmlsingle/#production-ready[actuator module], such as health, audits, beans, and more.
@@ -238,7 +238,7 @@ It's easy to check the health of the app.
238 238
 
239 239
 ----
240 240
 $ curl localhost:8080/health
241
-{"status":"UP"}
241
+{"status":"UP","diskSpace":{"status":"UP","total":397635555328,"free":328389529600,"threshold":10485760}}}
242 242
 ----
243 243
 
244 244
 You can try to invoke shutdown through curl.
@@ -295,7 +295,7 @@ $ curl localhost:8080
295 295
 Hello World!
296 296
 ----
297 297
 
298
-Spring Boot does this by dynamically adding key annotations to your code and leveraging http://groovy.codehaus.org/Grape[Groovy Grape] to pull down needed libraries to make the app run.
298
+Spring Boot does this by dynamically adding key annotations to your code and using http://groovy.codehaus.org/Grape[Groovy Grape] to pull down libraries needed to make the app run.
299 299
 
300 300
 == Summary
301 301
 Congratulations! You built a simple web application with Spring Boot and learned how it can ramp up your development pace. You also turned on some handy production services.

+ 19
- 10
complete/src/main/java/hello/Application.java Datei anzeigen

@@ -2,23 +2,32 @@ package hello;
2 2
 
3 3
 import java.util.Arrays;
4 4
 
5
+import org.springframework.boot.CommandLineRunner;
5 6
 import org.springframework.boot.SpringApplication;
6 7
 import org.springframework.boot.autoconfigure.SpringBootApplication;
7 8
 import org.springframework.context.ApplicationContext;
9
+import org.springframework.context.annotation.Bean;
8 10
 
9 11
 @SpringBootApplication
10 12
 public class Application {
11
-    
13
+
12 14
     public static void main(String[] args) {
13
-        ApplicationContext ctx = SpringApplication.run(Application.class, args);
14
-        
15
-        System.out.println("Let's inspect the beans provided by Spring Boot:");
16
-        
17
-        String[] beanNames = ctx.getBeanDefinitionNames();
18
-        Arrays.sort(beanNames);
19
-        for (String beanName : beanNames) {
20
-            System.out.println(beanName);
21
-        }
15
+        SpringApplication.run(Application.class, args);
16
+    }
17
+
18
+    @Bean
19
+    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
20
+        return args -> {
21
+
22
+            System.out.println("Let's inspect the beans provided by Spring Boot:");
23
+
24
+            String[] beanNames = ctx.getBeanDefinitionNames();
25
+            Arrays.sort(beanNames);
26
+            for (String beanName : beanNames) {
27
+                System.out.println(beanName);
28
+            }
29
+
30
+        };
22 31
     }
23 32
 
24 33
 }

+ 8
- 5
complete/src/test/java/hello/HelloControllerIT.java Datei anzeigen

@@ -8,31 +8,34 @@ import java.net.URL;
8 8
 import org.junit.Before;
9 9
 import org.junit.Test;
10 10
 import org.junit.runner.RunWith;
11
+import org.springframework.beans.factory.annotation.Autowired;
11 12
 import org.springframework.boot.context.embedded.LocalServerPort;
12 13
 import org.springframework.boot.test.context.SpringBootTest;
13 14
 import org.springframework.boot.test.web.client.TestRestTemplate;
14 15
 import org.springframework.http.ResponseEntity;
15
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
16
+import org.springframework.test.context.junit4.SpringRunner;
16 17
 
17
-@RunWith(SpringJUnit4ClassRunner.class)
18
-@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
18
+@RunWith(SpringRunner.class)
19
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
19 20
 public class HelloControllerIT {
20 21
 
21 22
     @LocalServerPort
22 23
     private int port;
23 24
 
24 25
     private URL base;
26
+
27
+    @Autowired
25 28
     private TestRestTemplate template;
26 29
 
27 30
     @Before
28 31
     public void setUp() throws Exception {
29 32
         this.base = new URL("http://localhost:" + port + "/");
30
-        template = new TestRestTemplate();
31 33
     }
32 34
 
33 35
     @Test
34 36
     public void getHello() throws Exception {
35
-        ResponseEntity<String> response = template.getForEntity(base.toString(), String.class);
37
+        ResponseEntity<String> response = template.getForEntity(base.toString(),
38
+                String.class);
36 39
         assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
37 40
     }
38 41
 }

+ 13
- 16
complete/src/test/java/hello/HelloControllerTest.java Datei anzeigen

@@ -4,31 +4,28 @@ import static org.hamcrest.Matchers.equalTo;
4 4
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
5 5
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
6 6
 
7
-import org.junit.Before;
8 7
 import org.junit.Test;
9 8
 import org.junit.runner.RunWith;
9
+import org.springframework.beans.factory.annotation.Autowired;
10
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
10 11
 import org.springframework.boot.test.context.SpringBootTest;
11 12
 import org.springframework.http.MediaType;
12
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
13
+import org.springframework.test.context.junit4.SpringRunner;
13 14
 import org.springframework.test.web.servlet.MockMvc;
14 15
 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
15
-import org.springframework.test.web.servlet.setup.MockMvcBuilders;
16 16
 
17
-@RunWith(SpringJUnit4ClassRunner.class)
17
+@RunWith(SpringRunner.class)
18 18
 @SpringBootTest
19
+@AutoConfigureMockMvc
19 20
 public class HelloControllerTest {
20 21
 
21
-	private MockMvc mvc;
22
+    @Autowired
23
+    private MockMvc mvc;
22 24
 
23
-	@Before
24
-	public void setUp() throws Exception {
25
-		mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
26
-	}
27
-
28
-	@Test
29
-	public void getHello() throws Exception {
30
-		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
31
-				.andExpect(status().isOk())
32
-				.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
33
-	}
25
+    @Test
26
+    public void getHello() throws Exception {
27
+        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
28
+                .andExpect(status().isOk())
29
+                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
30
+    }
34 31
 }