Quickly build a spring framework app with spring Boot-go

Source: Internet
Author: User
Tags tomcat server ruby on rails spring boot actuator

Original Address: https://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/

The Spring framework is no stranger to many Java Developers. Since its release in 2002, the Spring framework has become a very popular infrastructure in enterprise application Development. There are a number of enterprise applications that are developed based on the Spring Framework. The Spring framework contains dozens of different sub-projects that cover different aspects of application Development. So many sub-projects and components, on the one hand, to facilitate the use of developers, another aspect has also brought about the use of the Problem. Each sub-project has a certain learning Curve. Developers need to understand the specifics of these sub-projects and components in order to know how to integrate these sub-projects into a complete solution. There is no guidance on how to use these components with relevant best practices. For developers who are new to the Spring framework, they do not know how to better use these Components. Another common problem with the Spring framework is the hassle of quickly creating an application that can Run. Spring Boot is a new subproject of the spring framework that is used to create a spring 4.0 project. Its development began in the 2013. April 2014 released 1.0.0 Version. It automatically configures the various components of Spring and does not rely on code generation and XML configuration Files. Spring Boot also provides recommended component configurations for common Scenarios. Spring Boot can greatly improve development efficiency when using the spring Framework. This article provides a detailed introduction to Spring Boot.

Brief introduction

As you can see from boot in the Spring boot Project name, Spring boot works by creating and starting a new spring framework-based Project. It is designed to help developers easily create Spring-based frameworks for standalone runs and Product-level Applications. Spring Boot selects the most appropriate spring sub-project and third-party open source libraries for Consolidation. Most Spring Boot applications require very little configuration to run Quickly.

Spring Boot contains the following features:

    • Create a Spring app that can run Independently.
    • Embed a Tomcat or Jetty server directly without the need to deploy a WAR file.
    • Provides a recommended base POM file to simplify the Apache Maven Configuration.
    • Automatically configure the Spring framework based on project dependencies as much as Possible.
    • Provides features that can be used directly in a production environment, such as performance metrics, application information, and application health checks.
    • There is no code generation, and there is no XML configuration File.

With spring Boot, It is easy to create new spring applications, and the spring applications that are created conform to common best practices. Just a few simple steps to create a Web app. The Spring Boot app created using Maven as a build tool is described BELOW. Code Listing 1 shows the Application's POM File.

Listing 1. The POM file for the Spring Boot sample app
<?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.midgetontoes</groupid><artifactid>spring-boot-simple</artifactid><version>1.0- Snapshot</version><properties> <spring.boot.version>1.1.4.RELEASE</spring.boot.version> </properties><dependencies> <dependency> <groupid>org.springframework.boot</groupid > <artifactId>spring-boot-starter-web</artifactId> <version>${spring.boot.version}</ version> </dependency></dependencies><build> <plugins> <plugin> <groupId> Org.springframework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId>< Version>${spring.boot.version}</version> <executions> <execution> <goals> <goal>repackage</goal> </goals > </execution> </executions> </plugin> </plugins></build></project>

As you can see from the POM file in listing 1, the application claims few dependencies, only one "org.springframework.boot:spring-boot-starter-web", and not a lot of dependencies like other spring projects need to be declared. When you use the Maven command "MVN dependency:tree" to see the actual dependencies of a project, you will find that it contains dependencies such as the Spring MVC framework, slf4j, Jackson, Hibernate Validator, and Tomcat. This is actually a combination of open source libraries that are used in Spring recommended Web apps. Code Listing 2 shows the Java code for the sample Application.

Listing 2. Java code for the Spring Boot sample app
@RestController @enableautoconfigurationpublic class application {@RequestMapping ("/") String home () {return "Hello world! ";} public static void main (string[] Args) throws Exception {springapplication.run (application.class, args);}}

The Java class application in Code Listing 2 is a simple WEB application that can run Independently. Running the Java class directly will start an inline Tomcat server running on port 8080. Visit "http://localhost:8080" to see "Hello world!" displayed on the Page. That means you can launch a standalone Web app with just 2 Files. There is no need to install an application server such as Tomcat or to package it as a WAR file. You can start the app on the command line with "MVN spring-boot:run". The "org.springframework.boot:spring-boot-maven-plugin" plugin was added to the POM file in Listing 1. After the plugin is added, when the MVN package is run, it is packaged as a JAR file that can be run directly, and can be run directly using the "java-jar" command. This simplifies the deployment of the application to a great extent, and only installs the JRE to run it.

The "@EnableAutoConfiguration" annotations in Listing 2 are intended to allow spring Boot to automatically configure the spring framework based on the dependencies declared by the application, which reduces the Developer's workload. The annotations "@RestController" and "@RequestMapping" are provided by Spring MVC to create a REST service. These two annotations are not related to Spring Boot itself.

Spring Boot recommended base POM file

The "org.springframework.boot:spring-boot-starter-web" given in code Listing 1 in the previous section is one of the recommended base POM files provided by spring Boot to provide the creation of a W based on spring MVC Third-party Library dependencies required for EB applications. In addition to this pom file, Spring Boot also provides other similar Pom files. All of these base POM dependencies are in the "org.springframework.boot" Group. A description of some important POM files is shown in Table 1.

Table 1. Spring Boot recommended base POM file
name Description
Spring-boot-starter Core POM, which includes automatic configuration support, a log library, and support for YAML configuration Files.
Spring-boot-starter-amqp Support AMQP via Spring-rabbit.
Spring-boot-starter-aop Includes SPRING-AOP and AspectJ to support facet-oriented programming (aop).
Spring-boot-starter-batch Supports Spring Batch, including HSQLDB.
Spring-boot-starter-data-jpa Includes spring-data-jpa, spring-orm, and Hibernate to support Jpa.
Spring-boot-starter-data-mongodb Contains spring-data-mongodb to support Mongodb.
Spring-boot-starter-data-rest The Spring Data Warehouse is exposed in restful mode through SPRING-DATA-REST-WEBMVC support.
Spring-boot-starter-jdbc Supports access to the database using JDBC.
Spring-boot-starter-security Contains Spring-security.
Spring-boot-starter-test Contains the dependencies required for commonly used tests, such as JUnit, hamcrest, mockito, and Spring-test.
Spring-boot-starter-velocity Using Velocity as the template engine is Supported.
Spring-boot-starter-web Supports WEB application development, including Tomcat and spring-mvc.
Spring-boot-starter-websocket Support for developing WebSocket apps with Tomcat.
Spring-boot-starter-ws Supports Spring Web Services.
Spring-boot-starter-actuator Add features for your production environment, such as performance metrics and Monitoring.
Spring-boot-starter-remote-shell Add Remote SSH Support.
Spring-boot-starter-jetty Use Jetty instead of the default Tomcat as the application Server.
spring-boot-starter-log4j Added support for LOG4J.
Spring-boot-starter-logging Use the Spring Boot default log frame Logback.
Spring-boot-starter-tomcat Use Spring Boot default Tomcat as the application Server.

The benefit of all these POM dependencies is that it provides a good basis for developing Spring Applications. The Third-party library selected by Spring Boot is considered and is a better choice for product Development. But Spring Boot also offers different options, such as the log framework can be used with logback or log4j, and the application server can use Tomcat or Jetty.

Automatic configuration

Spring Boot's Greatest benefit for developers is the ability to automatically configure a spring Application. Spring Boot automatically configures the spring framework based on the Third-party dependencies declared in the app, without requiring explicit declarations. For example, when a dependency on HSQLDB is declared, Spring Boot is automatically configured to use HSQLDB for database operations.

Spring Boot recommends using Java annotations-based configuration instead of traditional XML. You only need to add "@EnableAutoConfiguration" annotations on the master configuration Java class to enable automatic Configuration. Spring Boot's auto-configuration feature is not intrusive, just as a basic default Implementation. Developers can override the functionality provided by automatic configuration by defining other Beans. For example, when the application has its own data source Bean defined, The HSQLDB provided by the automatic configuration will not take Effect. This gives developers a lot of Flexibility. You can quickly create a prototype application that can be run immediately, and can be constantly modified and adapted to suit the needs of application development at different Stages. Perhaps at the beginning of the application, the embedded memory database (such as HSQLDB) is sufficient, and later in the need to replace the MySQL Database. Spring Boot makes such a switch easy.

externally-configured Configuration

Managing configurations in your app is not an easy task, especially if your application needs to be deployed to multiple Environments. typically, you will need to provide a corresponding property file for each environment to configure your own database connection information, server information, and Third-party service Accounts. A common application deployment will include several environments such as development, testing, and Production. There is an overlay relationship between the configurations of different environments. The configuration in the test environment overrides the development environment, and the configuration in the production environment overrides the test Environment. The Spring framework itself provides a variety of ways to manage configuration Properties Files. You can use Propertyplaceholderconfigurer before Spring 3.1. Spring 3.1 introduces a new environment (environment) and profile API, which is a more flexible way to handle different environments and configuration Files. however, the problem with these configuration management methods in Spring is that there are too many choices to make developers at a loss. Spring Boot provides a unified way to manage the configuration of your app, allowing developers to define different priority configuration values using property files, YAML files, Environment variables, and command-line Parameters.

The configuration priority order provided by Spring Boot is more Complex. In order of precedence from highest to lowest, the specific list is as Follows.

    1. Command-Line Arguments.
    2. The Java system parameters obtained through System.getproperties ().
    3. Operating system Environment Variables.
    4. The JNDI attribute obtained from Java:comp/env.
    5. The "random.*" property generated by Randomvaluepropertysource.
    6. Apply a property file other than the Jar File.
    7. Apply the properties file inside the Jar file.
    8. A property file that is declared through the "@PropertySource" annotation in the application configuration Java class (the Java class that contains the "@Configuration" annotations).
    9. The default property declared by the "springapplication.setdefaultproperties".

This configuration priority of Spring Boot may seem complicated, but it's quite reasonable. For example, command-line parameters are set to the highest Priority. The benefit is that you can quickly modify configuration parameter values in a test or production environment without having to repackage and deploy the app.

The Springapplication class defaults to converting the command-line arguments that begin with "--" to the configuration parameters that can be used in the app, such as "--name=alex", which sets the value of the configuration parameter "name" to "Alex". If you do not need this feature, you can disable parsing of command-line arguments by using "springapplication.setaddcommandlineproperties (false)".

Randomvaluepropertysource can be used to generate a variety of different types of random values required for testing, eliminating the hassle of generating in code. Randomvaluepropertysource can generate numbers and strings. The type of the number contains int and long, which can limit the size range of the Number. With "random." The configuration property name as a prefix is generated by randomvaluepropertysource, as shown in code listing 3.

Listing 3. Configuration properties generated by using Randomvaluepropertysource
User.id=${random.value}user.count=${random.int}user.max=${random.long}user.number=${random.int (}user.range) =${random.int[100, 1000]}
Properties file

Property files are the most common way to manage configuration Properties. The Springapplication class provided by Spring Boot will search for and load the Application.properties file to get the configuration property Values. The Springapplication class searches for the file in the following Location.

    • The "/config" subdirectory of the current directory.
    • The current Directory.
    • The "/config" package in Classpath.
    • Classpath

The above order also indicates the priority of the properties file that is contained in the Location. Priority is arranged in order from highest to Lowest. You can specify a different property file name by using the "spring.config.name" configuration Property. You can also use "spring.config.location" to add additional properties to the File's search path. If you have multiple profiles in your app, you can define individual properties files for each profile and name them according to "application-{profile}".

For configuration properties, You can use "@Value" in your code, as shown in Listing 4.

Listing 4. Using the configuration properties with "@Value"
@RestController @enableautoconfigurationpublic class application {@Value ("${name}") private String name; Requestmapping ("/") String Home () {return String.Format ("Hello%s!", name);}}

In code listing 4, the value of the variable name comes from the "name" property in the configuration Property.

Yaml

YAML is a better configuration file format relative to the properties File. YAML is well-used in Ruby on Rails. The Springapplication class also provides support for YAML configuration files, just adding a dependency on the Snakeyaml. Code Listing 5 shows an example of the Application.yml File.

Listing 5. Configuration properties expressed with YAML
Spring:profiles:developmentdb:url:jdbc:hsqldb:file:testdb Username:sa Password:---spring:profiles:testdb:url:jdb C:mysql://localhost/test username:test Password:test

The Yaml file in Listing 5 also gives the configuration information for the development and test two different profiles, which is one of the advantages of the Yaml file relative to the properties File. In addition to using the @Value annotation binding to configure property values, you can use a more flexible Approach. The Code Listing 6 shows the Java class that uses the YAML file in code listing 5. With the @ConfigurationProperties (prefix= "db") annotation, The attribute value prefixed with "db" in the configuration attribute is automatically bound to a domain of the same name in the Java class, such as the value of the URL field corresponding to the property "db.url". You can enable the Auto-bind feature by simply adding the "@EnableConfigurationProperties" annotation to the App's configuration class.

Listing 6. Java classes that use YAML files
@Component @configurationproperties (prefix= "db") public class dbsettings {private string url; private String username; Private String password;}
Developing WEB applications

Spring Boot is ideal for developing spring MVC-based Web Applications. With an embedded Tomcat or Jetty server, You can simplify the deployment of your Web Application. Spring Boot provides some basic configuration for spring MVC applications through the auto-configuration feature, making it more suitable for general WEB application development Requirements.

Httpmessageconverter

The Httpmessageconverter interface is used in Spring MVC to convert message formats between HTTP requests and Responses. By default, JSON is supported by Jackson and XML format is supported via JAXB. You can add additional message format conversion implementations by creating a custom Httpmessageconverters.

static files

By default, Spring Boot can provide support for static files in the "/static", "/public", "/resources", or "/meta-inf/resources" directories. Spring Boot also supports Webjars. The contents under the path "/webjars/**" are provided by the Jar package in Webjar format.

Production environment operation and maintenance support

Unlike the development and Test environment, when an application is deployed to a production environment, it requires support for various operations-related features, including performance metrics, operational information, and application Management. All of these features have many technologies and open source libraries to Implement. Spring Boot integrates these operations-related functions into a fully functional and customizable feature set called Actuator. You can add actuator only by adding a dependency to the "org.springframe.boot:spring-boot-starter-actuator" in the POM file. After the actuator is added, some HTTP services are automatically exposed to provide this Information. Descriptions of these HTTP services are shown in table 2.

Table 2. The HTTP service provided by Spring Boot Actuator
name Description whether sensitive information is included
autoconfig Displays information about Spring Boot Auto-configuration. is
Beans Displays information about the Spring beans contained in the app. is
configprops displays the actual values of the configuration parameters in the app. is
dump to generate a thread dump. is
env Displays the environment configuration information obtained from Configurableenvironment. is
Health to display your app's healthy state Information. no
info Displays basic information about your app. no
metrics Displays the performance metrics for your app. is
mappings shows the path mappings that are added by the "
@RequestMapping" in the Spring MVC app.
is
shutdown close the app. is
trace to display app-related tracing (trace) Information. is

For each service in table 2, the relevant information can be obtained by accessing the URL of the Name. If you access "/info", you can get the information corresponding to the info service. Whether the service contains sensitive information indicates whether the information exposed by the service contains some more sensitive information to determine whether the appropriate access control needs to be added, rather than being exposed to EVERYONE. All of these services can be configured, such as changing the name to change the corresponding URL. A few important services are described BELOW.

Health services

Spring Boot provides the ability to detect the health of the app itself, relational database connections, MongoDB, Redis, and Rabbit MQ by Default. When the DataSource type of bean is added to the app, Spring Boot automatically exposes the database connection information in the health service. The app can also provide its own health status information, as shown in Listing 7.

Listing 7. Customizing the Health Service
@Componentpublic class Apphealthindicator implements Healthindicator {@Override Public health health () {return health.up (). Build (); }}

The application simply implements the Org.springframework.boot.actuate.health.HealthIndicator interface and returns a Org.springframework.boot.actuate.health.Health object, You can obtain the exposed information through the health Service. As shown in Listing 8.

Listing 8. Results returned by the health service
{"status": "up", "app": {"status": ' up '}, "db": {"status": "up", "database": "HSQL database Engine", "hello": 1}}
Info Service

The information exposed by the Info service is determined entirely by the Application. Any of the apps with "info." The initial configuration parameters are automatically exposed by the info service. Just add "info" to Application.properties. Start with the parameters, as shown in Listing 9.

Listing 9. Add the properties file for the configuration parameters required by the Info service
Info.app_name=my First Spring Boot applicationinfo.app_version=1.0.0

When you access "/info", the JSON data that is accessed is shown in code listing 10.

Listing 10. Results returned by the Info service
{"app_name": "My First Spring Boot application", "app_version": "1.0.0"}
Metrics Service

When accessing the metrics service, you can see the performance parameter values of some of the systems provided by Spring Boot through systempublicmetrics, including basic information on memory, CPU, Java class loading, and Threading. The app can record other information that it NEEDS. Spring Boot provides two types of performance metrics logging by default: gauge and Counter. Gauge is used to record a single absolute value, and counter is used to record increments or decrement values. For example, in a Web application, you can use counter to record the number of users currently ONLINE. When the user logs in, the value of counter is added to 1, and when the user exits, the counter value is reduced by 1. The Code Listing 11 shows an Example.

Listing 11. Custom Metrics Services
@RestControllerpublic class Greetingscontroller {@Autowired private Counterservice counterservice; @RequestMapping ("/ Greet ") public String greet () {counterservice.increment (" myapp.greet.count "); return" hello! ";}}

A dependency on the counterservice provided by Spring Boot was added in listing 11. When the greet method is called, the value of the counter named "myapp.greet.count" is incremented by 1. That is, when the user accesses "/greet" each time, the calculator will be added 1. In addition to counterservice, you can use Gaugeservice to record absolute values.

Using JMX for Management

The HTTP service exposed after adding actuator can only provide read-only Information. If you need to manage your app at run time, you need to use JMX. Spring Boot provides support for JMX management by Default. You can see the Mbean in the domain "org.springframework.boot" only if you connect to the Application's JMX server via the JConsole that comes with the JDK. You can create your own Mbean by using the @ManagedResource, @ManagedAttribute, and @ManagedOperation annotations provided by Spring.

Back to top of page

Using the Spring Boot CLI

Spring Boot provides a command-line tool to run Groovy Files. The installation of command-line tools is very simple and only needs to be decompressed after Downloading. See reference Resources. After decompression, you can run the Spring command to use the Tool. Apps developed with groovy are no different from using Java, except that using Groovy's simplified syntax can make the code simpler. Code Listing 12 shows the same Groovy implementation as the code Listing 2 Feature.

Listing 12. Sample apps that use Groovy
@RestControllerclass webapplication {@RequestMapping ("/") String home () {"Hello world!"}}

You only need to use spring run App.groovy to run the app. You can also use the DSL support provided by Groovy to simplify your application, as shown in Listing 13.

Listing 13. Simplify your app with Groovy DSL
@RestControllerclass webapplication {@Autowired Service service @RequestMapping ("/") String home () {service.greet ()}}c Lass Service {string message string greet () {message}}beans {service (service) {message = "another Hello"}}

In Listing 13, you can quickly create and configure Spring beans through the "beans" DSL.

Conclusion

Spring Boot is undoubtedly a very useful tool for developers who use the spring framework in General. This article details how to quickly create a spring application with spring boot and the capabilities it provides for automatic configuration and external configuration, as well as a description of the performance metrics provided by spring boot built-in actuator that can be used directly in the production environment, Functions such as running information and application management, and finally describes the use of the Spring Boot command-line Tool. The configuration of the Spring application is made simple with dependency-based auto-configuration Features. It's also easier to rely on management, without the need for developers to integrate Themselves. The functionality provided by actuator is very practical and is beneficial for monitoring and managing applications in a production Environment. Spring Boot should be a tool for every developer using the spring Framework.

Quickly build a spring framework app with spring Boot-go

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.