Quickly build spring framework applications with Springboot

Source: Internet
Author: User
Tags ruby on rails log4j

As you can see from the boot in the Springboot project name, Springboot's role is to create and launch a new spring-based framework project. It is designed to help developers easily create spring-based frameworks for standalone runs and product-level applications. Springboot will choose the most appropriate spring sub-project and third-party open source Library for consolidation. Most springboot applications require very little configuration to run quickly. Springboot 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 Springboot, 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 Springboot app created using Maven as a build tool is described below. code Example 1 gives the application's POM file. Example 1. Springboot the POM file for the sample application<?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 > from the POM file in code example 1, it can be seen that the application declares very few dependencies, only one "Org.springframework.boot:spring-boot-starter-web", Instead of having to declare a lot of dependencies like other spring projects. 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 SPRINGMVC framework, SLF4J, Jackson, Hibernate Validator, and Tomcat. This is actually a combination of open source libraries that are used in spring recommended Web apps. The Java code for the sample application is shown in code example 2. Example 2. Java code for the Springboot sample application@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 Example 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 code example 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 code example 2 are intended to allow Springboot 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 SPRINGMVC to create a REST service. These two annotations are not related to the springboot itself. Springboot recommended base POM filesThe "Org.springframework.boot:spring-boot-starter-web" given in code example 1 in the previous section is one of the recommended base POM files provided by Springboot to provide the creation of SPRINGMVC-based Third-party library dependencies required for WEB applications. In addition to this pom file, Springboot 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. Springboot Recommended base POM file 1.spring-boot-startercore POM, which includes automatic configuration support, a log library, and support for YAML configuration files. 2.spring-boot-starter-amqpsupport AMQP via Spring-rabbit. 3.spring-boot-starter-aopincludes SPRING-AOP and AspectJ to support facet-oriented programming (AOP). 4.spring-boot-starter-batchsupports Springbatch, including HSQLDB. 5.spring-boot-starter-data-jpaincludes SPRING-DATA-JPA, Spring-orm, and Hibernate to support JPA. 6.spring-boot-starter-data-mongodbcontains spring-data-mongodb to support MongoDB. 7.spring-boot-starter-data-restSpringdata warehouses are exposed in restful mode through SPRING-DATA-REST-WEBMVC support. 8.spring-boot-starter-jdbcsupports access to the database using JDBC. 9.spring-boot-starter-securitycontains spring-security. 10.spring-boot-starter-testcontains the dependencies required for commonly used tests, such as JUnit, Hamcrest, Mockito, and Spring-test. 11.spring-boot-starter-velocityusing Velocity as the template engine is supported. 12.spring-boot-starter-websupports WEB application development, including Tomcat and SPRING-MVC. 13.spring-boot-starter-websocketsupport for developing WebSocket apps with Tomcat. 14.spring-boot-starter-wssupport for Springweb Services. 15.spring-boot-starter-actuatoradd features for your production environment, such as performance metrics and monitoring. 16.spring-boot-starter-remote-shellAdd remote SSH support. 17.spring-boot-starter-jettyuse Jetty instead of the default Tomcat as the application server. 18.spring-boot-starter-log4jadded support for log4j. 19.spring-boot-starter-loggingUse the Springboot default log frame Logback. 20.spring-boot-starter-tomcatuse springboot 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 Springboot is considered and is a better choice for product development. But Springboot 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 ConfigurationSpringboot the biggest benefit for developers is the ability to automatically configure a spring application. Springboot 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, Springboot is automatically configured to use HSQLDB for database operations. Springboot 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. The Springboot 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. The springboot makes such a switch very simple. externally-configured configurationManaging 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. Springboot provides a unified way to manage the configuration of your application, allowing developers to define different priority configuration values using property files, YAML files, environment variables, and command-line parameters. The order of configuration precedence provided by the Springboot 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. JNDI properties 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. In the application Configuration Java class (the Java class containing the "@Configuration" annotations) is declared through the "@PropertySource" annotation of the properties file. 9. The default property declared by the "Springapplication.setdefaultproperties". This configuration priority of Springboot seems to be complex, in fact, it is very 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 use the Springapplication.setadDcommandlineproperties (FALSE) "Disables parsing of command-line arguments. 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 example 3. Example 3. Configuration properties generated using RandomvaluepropertysourceUser.id=${random.value}user.count=${random.int}user.max=${random.long}user.number=${random.int (}user.range) =${RANDOM.INT[100, 1000]} Properties FileProperty files are the most common way to manage configuration properties. The Springapplication class provided by Springboot 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 code example 4. Example 4. Using Configuration properties with "@Value"@RestController @enableautoconfigurationpublic class Application {@Value ("${name}") private String name; Requestmapping ("/") String Home () {return String.Format ("Hello%s!", name);}} In code instance 4, the value of the variable name comes from the "name" property in the configuration property. 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 Instance 5 gives an example of a application.yml file. Example 5. Configuration properties by using YAMLSpring:profiles:developmentdb:url:jdbc:hsqldb:file:testdb username:sa Password:---spring:profiles:testdb:url:jdb C:mysql://localhost/test username:test Password:test code Example 5 in the YAML file also gives the development and test two different profile configuration information, which is also YAM L file is one of the advantages relative to the properties file. In addition to using the @Value annotation binding to configure property values, you can use a more flexible approach. code example 6 gives the Java class that uses the YAML file in code instance 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. Example 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 ApplicationsSpringboot is ideal for developing SPRINGMVC-based WEB applications. With an embedded Tomcat or Jetty server, you can simplify the deployment of your WEB application. Springboot uses the automatic configuration feature to make some basic configuration of the SPRINGMVC application, making it more suitable for general WEB application development requirements. HttpmessageconverterThe 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 FilesBy default, Springboot can provide support for static files in the "/static", "/public", "/resources", or "/meta-inf/resources" directories. Springboot also supports Webjars. The contents under the path "/webjars/**" are provided by the Jar package in Webjar format. production environment operation and maintenance supportUnlike 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. Springboot integrates these operations-related functions and forms 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. The HTTP service provided by Table 2.SpringBootActuator name indicates whether sensitive information is included 1.autoconfigdisplays information about the Springboot auto-configuration. is a 2.beansdisplays information about the Springbean contained in the app. is a 3.configpropsdisplays the actual values of the configuration parameters in the app. is a 4.dumpgenerates a thread dump. is a 5.envDisplays the environment configuration information obtained from Configurableenvironment. is a 6.healthDisplays the health status information for the app. No 7.infodisplays basic information about your app. No 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 ServicesSpringboot default provides the ability to detect the health of the app itself, relational database connections, MongoDB, Redis, and Rabbit MQ. When a bean of type DataSource is added to the app, Springboot automatically exposes the database connection information in the health service. The app can also provide its own health status information, as shown in code example 7. Example 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 code example 8. Example 8. The results of the health service return{"Status": "Up", "app": {"status": ' Up '}, "db": {"status": "Up", "Database": "HSQL Database Engine", "Hello": 1}}info service Info The information exposed by the 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 arguments, as shown in code example 9. Example 9. Add the properties file for the configuration parameters required by the Info serviceInfo.app_name=my firstspringbootapplicationinfo.app_version=1.0.0 when accessing "/info", the JSON data is accessed as shown in code example 10. Example 10. Results returned by the Info service{"App_name": "My firstspringbootapplication", "app_version": "1.0.0"} Metrics ServiceWhen accessing the Metrics service, you can see some of the system's performance parameter values Springboot through Systempublicmetrics, including basic information about memory, CPU, Java class loading, and threading. The app can record other information that it needs. Springboot 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. Code Instance 11 gives an example. Example 11. Custom Metrics Service@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 Springboot has been added to code instance 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 ManagementThe 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. Springboot 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. using SPRINGBOOTCLISpringboot 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 example 12 gives the same Groovy implementation as the Code instance 2 feature. Example 12. Sample app using 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 code example 13. example 13. Simplifying 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 code instance 13, pass A "beans" DSL allows you to quickly create and configure Springbean. Springboot 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 springboot and the capabilities it provides for automatic configuration and external configuration, and also describes the Springboot built-in actuator provides performance metrics that can be used directly in the production environment, Functions such as running information and application management, and finally describes the use of the Springboot 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. Springboot should be used as a tool for every developer using the Spring framework.

Quickly build spring framework applications with Springboot

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.