天天看點

Spring Boot 項目建構 之 使用 Spring Boot 建構應用(Building an Application with Spring Boot)Building an Application with Spring Boot

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_what_you_ll_build">What you’ll build</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_what_you_ll_need">What you’ll need</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_how_to_complete_this_guide">How to complete this guide</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#scratch">Build with Gradle</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#use-maven">Build with Maven</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#use-sts">Build with Spring Tool Suite</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_learn_what_you_can_do_with_spring_boot">Learn what you can do with Spring Boot</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_create_a_simple_web_application">Create a simple web application</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_create_an_application_class">Create an Application class</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_run_the_application">Run the application</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_add_unit_tests">Add Unit Tests</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_add_production_grade_services">Add production-grade services</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_view_spring_boot_s_starters">View Spring Boot’s starters</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_jar_support_and_groovy_support">JAR support and Groovy support</a>

<a target="_blank" href="http://spring.io/guides/gs/spring-boot/#_summary">Summary</a>

<a target="_blank" href="http://spring.io/guides?filter=spring-boot">spring-boot</a>

<a target="_blank" href="http://projects.spring.io/spring-boot">Spring Boot</a>

<a target="_blank" href="http://spring.io/understanding/Git">Git</a>

GETTING STARTED

You’ll build a simple web application with Spring Boot and add some useful services to it.

About 15 minutes

A favorite text editor or IDE

To skip the basics, do the following:

cd into <code>gs-spring-boot/initial</code>

When you’re finished, you can check your results against the code in<code>gs-spring-boot/complete</code>.

In a project directory of your choosing, create the following subdirectory structure; for example, with <code>mkdir -p src/main/java/hello</code> on *nix systems:

<code>build.gradle</code>

It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.

It searches for the <code>public static void main()</code> method to flag as a runnable class.

Spring Boot offers a fast way to build applications. It looks at your classpath and at beans you have configured, makes reasonable assumptions about what you’re missing, and adds it. With Spring Boot you can focus more on business features and less on infrastructure.

For example:

Got Spring MVC? There are several specific beans you almost always need, and Spring Boot adds them automatically. A Spring MVC app also needs a servlet container, so Spring Boot automatically configures embedded Tomcat.

Got Jetty? If so, you probably do NOT want Tomcat, but instead embedded Jetty. Spring Boot handles that for you.

Got Thymeleaf? There are a few beans that must always be added to your application context; Spring Boot adds them for you.

These are just a few examples of the automatic configuration Spring Boot provides. At the same time, Spring Boot doesn’t get in your way. For example, if Thymeleaf is on your path, Spring Boot adds a <code>SpringTemplateEngine</code> to your application context automatically. But if you define your own <code>SpringTemplateEngine</code> with your own settings, then Spring Boot won’t add one. This leaves you in control with little effort on your part.

 Spring Boot doesn’t generate code or make edits to your files. Instead, when you start up your application, Spring Boot dynamically wires up beans and settings and applies them to your application context.

Now you can create a web controller for a simple web application.

<code>src/main/java/hello/HelloController.java</code>

The class is flagged as a <code>@RestController</code>, meaning it’s ready for use by Spring MVC to handle web requests. <code>@RequestMapping</code> maps <code>/</code> to the <code>index()</code> method. When invoked from a browser or using curl on the command line, the method returns pure text. That’s because<code>@RestController</code> combines <code>@Controller</code> and <code>@ResponseBody</code>, two annotations that results in web requests returning data rather than a view.

Here you create an <code>Application</code> class with the components:

<code>src/main/java/hello/Application.java</code>

<code>@SpringBootApplication</code> is a convenience annotation that adds all of the following:

<code>@Configuration</code> tags the class as a source of bean definitions for the application context.

<code>@EnableAutoConfiguration</code> tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.

Normally you would add <code>@EnableWebMvc</code> for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath. This flags the application as a web application and activates key behaviors such as setting up a <code>DispatcherServlet</code>.

<code>@ComponentScan</code> tells Spring to look for other components, configurations, and services in the the <code>hello</code> package, allowing it to find the <code>HelloController</code>.

The <code>main()</code> method uses Spring Boot’s <code>SpringApplication.run()</code> 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.

The <code>run()</code> method returns an <code>ApplicationContext</code> 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.

To run the application, execute:

If you are using Maven, execute:

You should see some output like this:

You can clearly see org.springframework.boot.autoconfigure beans. There is also a<code>tomcatEmbeddedServletContainerFactory</code>.

Check out the service.

You will want to add a test for the endpoint you added, and Spring Test already provides some machinery for that, and it’s easy to include in your project.

Add this to your build file’s list of dependencies:

If you are using Maven, add this to your list of dependencies:

Now write a simple unit test that mocks the servlet request and response through your endpoint:

<code>src/test/java/hello/HelloControllerTest.java</code>

Note the use of the <code>MockServletContext</code> to set up an empty <code>WebApplicationContext</code> so the <code>HelloController</code> can be created in the <code>@Before</code> and passed to<code>MockMvcBuilders.standaloneSetup()</code>. An alternative would be to create the full application context using the <code>Application</code> class and <code>@Autowired</code> the <code>HelloController</code> into the test. The <code>MockMvc</code> comes from Spring Test and allows you, via a set of convenient builder classes, to send HTTP requests into the <code>DispatcherServlet</code> and make assertions about the result.

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:

<code>src/test/java/hello/HelloControllerIT.java</code>

The embedded server is started up on a random port by virtue of the<code>@IntegrationTest("${server.port=0}")</code> and the actual port is discovered at runtime with the <code>@Value("${local.server.port}")</code>.

Then restart the app:

You will see a new set of RESTful end points added to the application. These are management services provided by Spring Boot.

It’s easy to check the health of the app.

You can try to invoke shutdown through curl.

Because we didn’t enable it, the request is blocked by the virtue of not existing.

The last example showed how Spring Boot makes it easy to wire beans you may not be aware that you need. And it showed how to turn on convenient management services.

But Spring Boot does yet more. It supports not only traditional WAR file deployments, but also makes it easy to put together executable JARs thanks to Spring Boot’s loader module. The various guides demonstrate this dual support through the <code>spring-boot-gradle-plugin</code> and<code>spring-boot-maven-plugin</code>.

On top of that, Spring Boot also has Groovy support, allowing you to build Spring MVC web apps with as little as a single file.

Create a new file called app.groovy and put the following code in it:

Run it as follows:

 This assumes you shut down the previous application, to avoid a port collision.

From a different terminal window: