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 文件中是额外指定配置,格式为缩进式