SpringBoot簡單搭建

1、創建一個maven工程

構建完成結構

2、搭建SpringBoot 項目

首先添加依賴pom.xml

<?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.cat.code</groupId>
    <artifactId>spring-boot-base-bulid</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

創建資源文件application.yml或者application.properties文件,但兩者配置格式不一樣

spring:
  application:
    name: base-bulid-spring-boot #服務名
server:
  port: 8084 #端口

啓動類【注意文件位置】

package com.cat.code;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author: lvgang
 * @Time: 2019/9/27 16:13
 * @Description: todo
 */
@SpringBootApplication
public class BaseBuildSpringBootApplication {

    public static void main(String[] args){
        SpringApplication.run(BaseBuildSpringBootApplication.class,args);
    }
}

controller層

package com.cat.code.controller;

import com.cat.code.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: lvgang
 * @Time: 2019/9/27 16:19
 * @Description: todo
 */
@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("/test")
    public String test(){
        return testService.test();
    }

}

service層

package com.cat.code.service;

import org.springframework.stereotype.Service;

/**
 * @Author: lvgang
 * @Time: 2019/9/27 16:19
 * @Description: todo
 */
@Service
public class TestService {

    public String test(){
        return "ok";
    }
}

最後啓動啓動類的主函數,在瀏覽器訪問http://localhost:8084/test即可訪問

 

【注】

1、@service所註解的類名不可以與spring自帶的類名相同,不然會出現

Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'xxxService' is expected to be of type 'yyy' but was actually of type 'zzz'

2、springboot項目可以自動掃描組件是因爲啓動添加了註解@SpringBootApplication,可以看到該註解源碼包含自動配置和組件掃描等註解功能

3、application.yml 文件中是額外指定配置,格式爲縮進式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章