Chapter II A second SPRING-BOOT procedure

Source: Internet
Author: User

The code in the previous section is a starter program for Spring-boot and a program on the official documentation. This section introduces the way in which Spring-boot official documentation is recommended to develop the code and introduces our call to the service layer in spring development.

1, the code structure is as follows

2, Pom.xml

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "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/maven-v4_0_0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Com.xxx</groupId>    <Artifactid>Myboot</Artifactid>    <version>1.0-snapshot</version>    <Properties>        <java.version>1.8</java.version><!--Official recommendation -    </Properties>    <!--introducing Spring-boot-starter-parent As the parent is the best way, but sometimes we might want to introduce our own parent, at which point there are two ways to solve it: 1) The pom.xml of our own parent     The parent is set to spring-boot-starter-parent (not verified, but it feels doable) 2) use the springboot in the documentation: see Spring-boot-1.2.5-reference.pdf on page 13th  -    <Parent>         <groupId>Org.springframework.boot</groupId>         <Artifactid>Spring-boot-starter-parent</Artifactid>         <version>1.2.5.RELEASE</version>     </Parent>    <!--<dependencyManagement> <dependencies> <dependency> Import Dependen Cy Management from Spring Boot <groupId>org.springframework.boot</groupId> <a                Rtifactid>spring-boot-dependencies</artifactid> <version>1.2.5.RELEASE</version>        <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> -    <!--Introduce actual dependencies -    <Dependencies>        <Dependency>            <groupId>Org.springframework.boot</groupId>            <Artifactid>Spring-boot-starter-web</Artifactid>        </Dependency>    </Dependencies>    <Build>        <Plugins>            <!--The jar used to make the application run directly (the jar is used in a production environment) it is worth noting that if you do not refer to Spring-boot-starter-parent as the parent and use the second method described above, it is also To make the appropriate changes -            <plugin>                <groupId>Org.springframework.boot</groupId>                <Artifactid>Spring-boot-maven-plugin</Artifactid>            </plugin>        </Plugins>    </Build></Project>
View Code

Description: The Pom.xml file is exactly the same as in the previous section.

3, Application.java

Package Com.xxx.firstboot;import Org.springframework.boot.springapplication;import org.springframework.boot.autoconfigure.springbootapplication;/** * @EnableAutoConfiguration: Spring boot annotations, Typically used only in the main class, * is a critical part of no XML configuration startup, explicitly specifying the package that scans the path of the package for the main class it decorates (which is why the main class is being placed under the root package path) *  * @ComponentScan to scan the package, Scan path specified by @enableautoconfiguration *  * Main class to be located under the root package path, convenient after the scan (We generally recommend that you locate your main application Class in a root package above other classes.) */@SpringBootApplication        //same as @[email Protected][email protected]public class Application {    /**     * Spring boot entry, within the entire subproject,     * There can be only one main method, otherwise spring boot does not start     *    /public static void main (string[] args) {        Springapplication.run (Application.class, args);}    }
View Code

Attention:

    • The main class is to be located under the root package path (for example, Com.xxx.firstboot), which is a recommended practice for easy scanning
    • Each jar (that is, each subproject) must have a master method to start the jar (that is, a microservices)
    • Add an annotation @springbootapplication to the main class, which is equivalent to adding three annotations as follows
      • @Configuration: This note indicates that the class is managed by the spring container
      • @EnableAutoConfiguration: This annotation is a critical part of starting without XML configuration
      • @ComponentScan: The note specifies the scan package (if the main class is not located under the root path, you need to specify a scan path), similar to the Spring package scan annotations

4, Application.properties

1 #user info2 user.id=13 User.username=zhaojigang4 user.password=123
View Code

Attention:

    • The Application.properties file is the default file for Spring-boot, and the general configuration (including: Data source configuration, httpclient configuration, etc.) is all right here.

5, User.java

 PackageCom.xxx.firstboot.domain;Importorg.springframework.boot.context.properties.ConfigurationProperties;Importorg.springframework.stereotype.Component;/*** @ConfigurationProperties (prefix= "user") * automatically read application.properties (is the spring-boot default lookup file) in the user.* attribute of the file * Without using @configurationproperties, you can use @value ("${user.id}") to specify the value of the attribute * * Note: If you want to use @configurationproperties and @value, You need to add the bean @component, * because in the back of the use of the class, you need to directly use the class @autowire annotation injection, so that the automatic injection of these properties will work, * use to see "UserService"*/@Component @configurationproperties (prefix= "User") Public classUser {//@Value ("${user.id}")    Private intID; //@Value ("Wangna")    PrivateString username; PrivateString password;  Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; }}
View Code

Attention:

    • This class is an ordinary model, in the SSM framework we do not have this model to the spring container to manage, here using the @component annotation to the spring container to handle, so in later use, You can inject the model directly into its use class.
    • A @configurationproperties (prefix= "user") annotation was added to the class. This means that the configuration of the Application.properties file-related prefixes can be automatically scanned and configured to each property of the class according to the name
    • You can also use @value annotations on attributes to separate complex values, assuming that there is no configuration @configurationproperties, if configured, @Value annotations fail

6, Userservice.java

 Package Com.xxx.firstboot.service; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.Service; Import Com.xxx.firstboot.domain.User; @Service  Public class userservice {        @Autowired    private  user user;          Public User GetUser () {        return  user;    }}
View Code

Attention:

    • This is directly injected into the user, and the class is the model

7, Usercontroller.java

 PackageCom.xxx.firstboot.web;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;ImportCom.xxx.firstboot.domain.User;ImportCom.xxx.firstboot.service.UserService;/*** @RestController: Spring MVC annotations, * equivalent to @controller and @responsebody, can be returned directly to JSON*/@RestController @requestmapping ("/USER") Public classUsercontroller {@AutowiredPrivateUserService UserService; @RequestMapping ("/getuser")     PublicUser GetUser () {returnUserservice.getuser (); }}
View Code

Description

    • This class is actually the most basic and most common way to develop a spring-boot program. (in microservices applications, the development of a parent-child module similar to the "Java Enterprise application Development Practice" series)
    • Spring-boot's way to read properties files is fairly easy relative to SSM, with three common ways to read property files
      • Use Fileutil to read: See chapter I Properties File Operations Tool class
      • Use the annotation implementation as above (the most recommended way)
      • Use the environment class to get the line (this may be the wrong class name)

For Spring-boot, which itself has many integrated jar packages (see below), we can introduce the appropriate jar according to our own needs, but there is no jar integrated with MyBatis.

Spring-boot dependent packages (which can be introduced on demand):

Chapter II A second SPRING-BOOT procedure

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.