Quickly build apps with spring boot

Source: Internet
Author: User

http://www.infoq.com/cn/news/2014/01/spring-boot/

With the release of the new Spring 4 release, Spring Boot's new sub-project has received a wide range of attention, as both the Spring 4 official press release and the interview with the chief architect, Adrian Colyer, have praised the productivity gains of this subproject.

Spring boot takes full advantage of the Javaconfig configuration model and the concept of "convention over Configuration", which greatly simplifies the development of Web applications and rest services based on spring MVC.

Spring 4 advocates the architecture of microservices, and in response to this philosophy, there have been some valuable discussions on Weibo recently, such as here and here. The MicroServices architecture advocates the ability to split functionality into discrete services and deploy it independently, and Spring boot makes it easy to package applications into separate, runnable jar packages, so it fits in the development model. Currently, Spring Boot is still a milestone version of 0.5.0, so the relevant documentation is not yet complete, and this article will introduce a simple sample of the development process based on this project.

For feature development with spring boot, you need to use Gradle or Maven as the build tool. In this example, we'll use Eclipse and Maven plug-ins for development. To use spring Boot, first create a MAVEN project and modify the MAVEN main configuration file, Pom.xml, as follows:

<parent> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter- parent</artifactid> <version>0.5.0.M7</version> </parent> <dependencies> < Dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot -starter-web</artifactid> </dependency> <dependency> <groupid>org.thymele af</groupid> <artifactId>thymeleaf-spring3</artifactId> </dependency> </de pendencies> <properties> <start-class>com.levin.Application</start-class> </propertie s> <build> <plugins> <plugin> <groupid>org.springframework. Boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> &LT;/PLUGIN&G        T </plugins&gT            </build> <repositories> <repository> <id>spring-milestone</id> <url>http://repo.spring.io/libs-milestone</url> <snapshots> <enabled> false</enabled> </snapshots> </repository> </repositories> <pluginrepos itories> <pluginRepository> <id>spring-milestone</id> <url>http://             Repo.spring.io/libs-milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories>

In the above configuration, you need to set the project's parent to spring-boot-starter-parent and add a dependency on spring-boot-starter-web so that we don't have to set up individual dependencies and their version information. And in the build to declare the use of Spring-boot-maven-plugin this plug-in, it will be the MAVEN packaging formed Jar made two changes, and ultimately produce a content structure that meets our requirements.

In our app, we're going to publish a rest service that shows a basic user information, first defining a simple model class:

Package Com.levin;public class Person {private String name;private string email;public Person (string name, string email) { this.name = Name;this.email = email;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;}}

Next, we need to declare a spring MVC controller that responds to requests for entities:

@Controllerpublic class Showpersoncontroller {    @RequestMapping ("/showperson") public    @ResponseBody Person Showperson () {        return new person ("Levinzhang", "[email protected]");}    }

This class does not differ from the one we use to define a controller with spring MVC. Next, we need to declare a main class to launch this application:

@ComponentScan @enableautoconfigurationpublic class Application {public    static void Main (string[] args) {        Springapplication.run (Application.class, args);}    }

The Springapplication helper class is used in the main method of this class, and the application class is configured to start the Spring application context. The Componentscan and enableautoconfiguration annotations are used in this class, where the Componentscan annotation tells spring to scan the specified package to initialize the spring Bean. This ensures that the beans we declare can be discovered. Enableautoconfiguration will start the auto-configuration mode, which will cascade the Tomcat dependency in our configuration, so an embedded tomcat will be started automatically when the app starts, because spring MVC is used in the sample. As a result, the required Dispatcherservlet are also automatically registered, which does not require a configuration like Web. Xml.

To run this application in Eclipse, you can run the main function directly in Java application, which launches the application, and we can see the following running effect in the browser, which is the rest service we want:

After the development debugging is complete, you can make the app into a jar package, and in eclipse you can directly use the MAVEN plugin's Package command, eventually forming a runnable jar. We can run the jar package with the Java–jar command. The effect is the same as during the commissioning period. Now look at the directory structure of this jar package after decompression:

This jar differs from the traditional jar package in that it has a directory called LIB, which contains the other jar packages that the simple application relies on, including the built-in embedded Tomcat, which is used to publish services and access Web resources. In addition to the class created by the source code we have compiled, there are many classes provided by spring in the Org directory, and it is the class that relies on these class to be able to load in the jar in the Lib directory. Such a loading mechanism is similar to declaring Bundle-classpath in an OSGi bundle, but in OSGi it is the container that is responsible for loading the classes under the specified path. This outlines the reasons why a jar package can publish a service.

If we want to use HTML, JSP and other Web resources, we can directly return the corresponding view in the controller.

If we want to convert this jar package into a war that can be deployed in a servlet container, we can't rely on the main function of application. Instead, to start the spring application context in a manner similar to the Web. xml file configuration, we need to declare a class like this:

public class Hellowebxml extends Springbootservletinitializer {    @Override    protected Springapplicationbuilder Configure (Springapplicationbuilder application) {        return application.sources (Application.class);    }}

The role of this class is similar to configuring the Listener in Web. Xml to initialize the spring application context, except that there is no need to write additional XML files here.

If you want to change the final packaging form to a war, you also need to modify the Pom.xml file, in addition to modifying the value of packaging to war, you need to configure the dependency appropriately (this part is not mentioned in the Spring boot sample and documentation. To remind everyone to note):

<dependency>            <groupId>org.springframework.boot</groupId>            <artifactId> spring-boot-starter-web</artifactid>            <exclusions>           <exclusion>           <groupId> Org.springframework.boot</groupid>        <artifactId>spring-boot-starter-tomcat</artifactId>           </exclusion>           </exclusions> </dependency>

There is a need to remove the dependency on embedded Tomcat, so that in the war package, the Tomcat-related jar package will not be included in the Lib directory, or a startup error may occur. In addition, after removing the dependency on Tomcat, in order to ensure that the compilation is correct, you also need to add a dependency on Servlet-api, so add the following configuration:

<dependency>        <groupId>org.apache.tomcat</groupId>        <artifactId> tomcat-servlet-api</artifactid>        <version>7.0.42</version>        <scope>provided </scope></dependency>

Set the scope property here to provided so that the jar package will not be included in the resulting war, because servers such as Tomcat or jetty will provide the relevant API classes at runtime. At this point, the Execute MVN Package command will get a war file that we can directly put under Tomcat (requires 7.0.42 or more).

The above describes the process of developing an application based on spring boot, and its documentation is not yet complete, but there are a number of examples on GitHub, including integrated access to the database with spring data (relational and non-relational), security, WebSocket, and so on, readers interested in downloading and running , it should be noted that some examples use the 0.5.0.M6 version, this version has a problem, the runtime will be wrong, it is recommended to manually modify the 0.5.0.M7 or snapshot version.

Based on the above introduction, I hope the reader can understand the new project of Spring boot. It simplifies the configuration of jar package management and associated infrastructure environments, helps us to quickly develop Web applications or build rest services, and hopefully it will be as mature as possible, more in practice, and more efficient in development.

Resources

http://projects.spring.io/spring-boot/

Http://projects.spring.io/spring-boot/docs/README.html

http://spring.io/guides/gs/spring-boot/

http://spring.io/guides/gs/actuator-service/

http://spring.io/guides/gs/convert-jar-to-war/

Quickly build apps with spring boot

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.