使用SpringBoot入門案例


一、創建項目

  今天給大家講一個SpringBoot的一個入門案例,讓更多人能用起SpringBoot來。假設項目名為MyProject項目,並添加MyProject-Web的子模塊。

二、給根項目MyProject的pom.xml,加入parent節點(spring-boot-starter-parent)

    <!--Add Spring boot Parent-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>

三、為子模塊MyProject-Web的pom.xml添加下列依賴

    <dependencies>
        <!--SpringBoot核心模塊,包括自動配置支持、日志和YAML-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--Web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--測試模塊,包括JUnit、Hamcrest、Mockito-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--加載yml配置文件使用。-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <!--自動Get、Set-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

四、添加項目包,整理項目結構

說明,子模塊的pom中加入的依賴項:spring-boot-starter-test、spring-boot-configuration-processor、lombok不是必需的。因為演示例子中,加入了對yml配置轉換為封裝實體的樣例。所以加入了spring-boot-configuration-processor、lombok。

 

五、在build包下加入ApplicationServer.java的結構如下:

package com.test.build;

import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;


@ComponentScan({"com.test"})
@SpringBootApplication
@PropertySource({"classpath:config/resource.properties"})
public class ApplicationServer {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(ApplicationServer.class);
        application.setBannerMode(Banner.Mode.OFF);//關閉啟動時的Banner展示
        application.run(args);

        //等價用法
        //SpringApplication.run(ApplicationServer.class, args);
    }
}

 

六、在resources/application.yml中結構如下:

server:
  address: 0.0.0.0
  port: 8080
  servlet:
    context-path: /app
  tomcat:
    uri-encoding: utf-8


constant:
  company: testttttt
  address: 北京市上地九街數碼科技廣場XXXXXX

七、在resources/config/resource.properties中結構如下:

person.name: Sindrol

 

八、在constant常量文件夾下ConstantSetting.java中結構如下:

package com.test.constant;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "constant")
public class ConstantSetting {
    private String company;
    private String address;
}

注意,這里使用的@ConfigurationProperties用來標注一個類,上文中將yml中前綴為constant的值映射到此實體中,它需要spring-boot-configuration-processor包依賴。@Data 是為實體類自動生成get、set。

 

九、在config夾中ApplicationConfig.java類中,內容如下:

package com.test.config;

import com.test.constant.ConstantSetting;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ApplicationConfig {
    public ApplicationConfig() {
        System.out.println("ApplicationConfig inited ...");
    }

    @Bean
    public ConstantSetting constantSetting() {
        return new ConstantSetting();
    }
}

說明:@Configuration表示一個Spring的xml配置文件。@Bean表示Spring的配置文件中的Bean配置。

十、簡單調用

在domain中添加一實體:TestEntry.java,內容如下:

package com.test.domain;

import lombok.Data;

@Data
public class TestEntry {
    private Integer id;
    private String name;
}

 

在controller中建一個HelloController控制器,然后內容如下:

package com.test.controller;

import com.test.constant.ConstantSetting;
import com.test.domain.TestEntry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.Nullable;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.RequestScope;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.ref.ReferenceQueue;
import java.nio.file.Files;
import java.util.List;

@RestController
public class HelloController {

    /*
     * 在ApplicationServer中使用了PropertySource配置了properties源后,從相應的源如resource.properties中加載值。
     * */
    @Value("${person.name}")
    private String name;

    /*
     *  Autowired區別於Resource的不同處在於,Autowired是按類別導入,如果想指定名稱,可以配合Qualifier使用。
     * */
    // @Autowired
    // @Qualifier("constantSetting")
    @Resource
    private ConstantSetting constantSetting;

    /*
     * 最簡單的使用
     * */
    @RequestMapping("/hello")
    public String hello() {
        return "hello " + name + " !" + " from company " + constantSetting.getCompany();
    }

    /*
     * 系統自動直接將實體序列化為JSON返回。
     * */
    @RequestMapping("/constant")
    @ResponseBody //相當於把結果JSON處理后返回。
    public ConstantSetting constant() {
        return constantSetting;
    }

    /*
     * 當使用Post請求,Content-Type=application/json調用測試: {"id":1,"name":"Sindrol"}
     * */
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    @ResponseBody
    public TestEntry constant(@RequestBody TestEntry test) {
        return test;
    }

    /*
     * 當使用Get請求
     * */
    @GetMapping(value = "/test")
    @ResponseBody
    public TestEntry constant(@RequestParam int id, @RequestParam String name) {
        TestEntry test = new TestEntry();
        test.setId(id);
        test.setName(name);
        return test;
    }

    /*
     * 當使用Get請求,並設置響應狀態
     * */
    @GetMapping(value = "/request")
    @ResponseBody
    public TestEntry request(HttpServletRequest request, HttpServletResponse response, @RequestParam int id, @RequestParam String name) {
        response.setStatus(500);
        TestEntry test = new TestEntry();
        test.setId(id);
        test.setName(name);
        return test;
    }

    /*
     * 當使用Post請求表單類型,傳送的值可空
     * */
    @PostMapping(value = "/form")
    @ResponseBody
    public TestEntry form(@Nullable @RequestParam("id") Integer id, @Nullable @RequestParam("name") String name) {
        TestEntry test = new TestEntry();
        test.setId(id);
        test.setName(name);
        return test;
    }

    /*
     * 當使用Post請求form-data表單類型,注意在使用PostMan測試時,不要添加Content-Type頭,會影響上傳時真正使用的Content-Type的
     * */
    @PostMapping(value = "/file")
    public String form(@RequestParam("filename") MultipartFile file) {
        return "fileName:" + file.getOriginalFilename() + " fileSize:" + file.getSize() + " contentType:" + file.getContentType();
    }
}

 

 

十一、運行ApplicationServer.java中的Main函數,並在瀏覽器中訪問 http://127.0.0.1:8080/app/hello 即可看到效果.(中間的app虛擬應用名稱是在application.yml中的server.servlet.context-path節點配置的)

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM