Spring Boot Learning Notes

Source: Internet
Author: User
Tags mongodb driver mongodb support

What is Spring boot?

Spring Boot is a new framework provided by the pivotal team designed to simplify the initial setup and development of new spring applications.
Spring boot uses the concept of "contract better than configuration" to reduce the cumbersome configuration of spring and to quickly build applications
Spring Boot official website: http://projects.spring.io/spring-boot/

MAVEN configuration:
<parent>    <groupId>org.springframework.boot</groupId>    <artifactId> Spring-boot-starter-parent</artifactid>    <version>1.2.5.RELEASE</version></parent> <dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency></dependencies>

  

Configuration interpretation:

    • After inheriting spring-boot-starter-parent, we can inherit some default dependencies so that we don't need to add a bunch of dependencies to minimize the dependency configuration.
    • Spring-boot-starter-web provides support for the web, with embedded Tomcat containers and endpoint information such as server information, application metrics (metrics), and environmental details
Hello World

Hello-world in the official website, examples are as follows:

Package Hello;import Org.springframework.boot.*;import Org.springframework.boot.autoconfigure.*;import Org.springframework.stereotype.*;import org.springframework.web.bind.annotation.*; @Controller  // Identity is the controller class for the Web @enableautoconfiguration//Allow auto-load configuration, boot to configure the application in a specific way public class Samplecontroller {    @ Requestmapping ("/")//corresponds to the relative directory of the restful URL    @ResponseBody//will return the body    String Home () {        return ') directly as response Hello world! ";    }    Start application public    static void Main (string[] args) throws Exception {        Springapplication.run ( Samplecontroller.class, args);}    }
Main separation

When you have multiple controllers, it is inappropriate to put main directly inside a controller, then split main separately.

Usercontroller.class:

Package Sailorxiao. Springbootsample.controller; The agreed controller is placed in the Controller directory import Org.springframework.boot.*;import org.springframework.boot.autoconfigure.* ; Import Org.springframework.stereotype.*;import org.springframework.web.bind.annotation.*;@ Controller@requestmapping ("/user") @EnableAutoConfigurationpublic class Usercontroller {public    String Hellouser () {        return "Hello user!";    }} Main:package Sailorxiao. Springbootsample; The default main class should be placed in the first-level directory of the project SRC code, using the default Applicationimport org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.enableautoconfiguration;import Org.springframework.context.annotation.ComponentScan, @EnableAutoConfiguration @componentscanpublic class Application {public    static void Main (string[] args) {        springapplication.run (application.class, args);}    }

  

, for the main function, it cannot be placed in a separate controller, so:

    • @EnableAutoConfiguration symbol on the corresponding main class
    • @ComponentScan allow boot to scan a bean in a project based on Convention rules
Increased @autowired Automatic assembly

Usually in the controller there will be some logical interaction, need to do some processing (such as read and write DB, some business logic, etc.), will generally put the relevant operations under the corresponding service, such as the next, usercontrller processing, increase UserService
Usercontroller:

Package Sailorxiao. Springbootsample.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import Sailorxiao. Springbootsample.entity.user;import Sailorxiao. Springbootsample.service.ihelloservice;import Sailorxiao. SpringBootSample.service.IUserService; @RestControllerpublic class Usercontroller {    @Autowired    private Iuserservice UserService; Using automatic equipment, boot will automatically assemble the corresponding service object    @RequestMapping ("/hello/{name}")//Rest path with name, the full URL is http://xxxx/user /{name} public    string Hellouser (@PathVariable ("name") string name) {        return Userservice.hellouser (name);}    }

  

Under Service directory

Iuserservice:

Package Sailorxiao. Springbootsample.service; All service contracts are placed in the Service directory public interface Iuserservice {//For each service need to define good one interface, directly placed in the service directory, The name is Ixxxservice public    string Hellouser (string user);}

  

Iuserserviceimpl:

Package Sailorxiao. Springbootsample.service.impl;import Org.springframework.stereotype.component;import Sailorxiao. SpringBootSample.service.IUserService; @Component//need to add this tag so that the componentscan of main can be scanned to the corresponding implementation public class Userserviceimpl implements Iuserservice {    @Override public    string Hellouser (string user) {        return "Hello" + user;    }}
HTTP body Constraint

Many times, you will want to pass in a specific rule parameter, for example, we want to pass in the user object {name:xxx,age:xxx} in Usercontroller
Controller

Package Sailorxiao. Springbootsample.controller;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.bind.annotation.*;import Sailorxiao. Springbootsample.entity.user;import Sailorxiao. SpringBootSample.service.IUserService; @RestControllerpublic class Usercontroller {    @Autowired    private Iuserservice UserService;    @RequestMapping ("/hello/{name}") Public    string Hellouser (@PathVariable ("name") string name) {        return Userservice.hellouser (name);    }    @RequestMapping (value = "/create", method = requestmethod.post) public    User createUser (@RequestBody user user) {        return Userservice.createuser (user);}    }

  

User object:

Package Sailorxiao. springbootsample.entity; Generally user-related objects are placed in the Entity directory public class User {//user object is a bean, there is a default Set/get method    private String name;    private int age;    Public String GetName () {        return this.name;    }    public void SetName (String name) {        this.name = name;    }    public int getage () {        return this.age;    }    public void Setage (int.) {        this.age = age;    }}

  

Note that when the client uses JSON as the body passed to the server controller, it needs to flag contenttype as "Application/json", as in the following way:

HttpClient HttpClient = new HttpClient (); Stringrequestentity requestentity = new Stringrequestentity (        jsonstr,//JSON serialized string, For example, this should be the user object serialized into JSON str        "Application/json",        "UTF-8"); Postmethod Postmethod = new Postmethod (URL);p ostmethod.setrequestentity (requestentity); Httpclient.executemethod ( Postmethod); String resstr = postmethod.getresponsebodyasstring (); System.out.println ("Post res:" + resstr);
Resource

Sometimes it is necessary to use configuration, so it is very simple to use the configuration in boot, as follows, after defining the configuration, only need to declare in the program

Application.properties:host= "192.168.137.10" Port=34001properties class: @ConfigurationProperties// Declare that this is the properties of the Beanpublic class Bootmongoproperties {    private String host;    private int port;    Public String GetHost () {        return this.host;    }    public void Sethost (String host) {        this.host = host;    }    public int Getport () {        return this.port;    }    public void Setport (int port) {        this.port = port;    }}

  

If the configuration is preceded by a certain name, you can add the prefix field, such as:

@ConfigurationProperties (prefix = "spring.data.mongodb") public    class Bootmongoproperties {        private String Host Indicates that the configuration item is spring.data.mongodb.host        private int port;        Private String uri = "Mongodb://localhost/test"; If Spring.data.mongodb.uri is not configured in the configuration, the default value is public        String gethost () {            return this.host;        }        public void Sethost (String host) {            this.host = host;        }        public int Getport () {            return this.port;        }        public void Setport (int port) {            this.port = port;        }    }
MongoDB Support

In general, the use of the Web services to the DB, then the spring boot inside how to do the db-related operations? Take MongoDB For example, only need three department

The first step is to configure the DB-related configuration to configure the MongoDB URI in Application.properties

spring.data.mongodb.uri=mongodb://sailor:[email protected]:34001/sailor?autoConnectRetry=true&connectTimeout=60000spring.data.mongodb.repositories.enabled=true

The second step, the declaration of MONGOTEMPLATE,MONGODB driver, related operations are carried out through mongotemplate

@Resource  // @Resource表示mongoTemplate直接基于配置生成对应的mongoTemplate操作实例private MongoTemplate mongoTemplate;

Step three, use Mongotemplate

User user = new User (name, age); Define a collection-related beanmongotemplate.insert (user); Insert the data from the MONGO into the user's corresponding class name set (here is User) User class: public class    user {        private String name;        private int age;        Public user () {            //Do not        } public        User (String name, int age) {            this.name = name;            This.age = age;        }        Public String GetName () {            return this.name;        }        public void SetName (String name) {            this.name = name;        }        public int getage () {            return this.age;        }        public void Setage (int.) {            this.age = age;        }    }

  

With the above three steps, it is easy to implement the DB of the boot operation

Problem when running through Java-jar, the main function is not found

Solution, add the MainClass option in Pom.xml to indicate the corresponding MainClass

<build><plugins>        <plugin>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-maven-plugin</artifactId>            <configuration>                <mainclass >SailorXiao.spring.main.Main</mainClass>            </configuration>        </plugin>    </ Plugins></build>

  

Spring Boot Learning Notes

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.