新手教程系列——SpringBoot基础

SpringBoot基础

1. 初始化项目

方法1:从SpringBoot官网下载初始化项目:https://start.spring.io/,选择自己需要添加的依赖,下载到本地即可。
方法2:从idea中新建:create new project —>Spring Initializr,然后选择自己需要的依赖即可。
方法3:手工搭建一个SpringBoot项目:新建maven工程—>手工在pom文件里写入基本的相关依赖。

	 <!-- 依赖一个parent可以不用写版本 -->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 前端thymeleaf模板引擎依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>  
        <!-- 阿里的数据库连接池依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.18</version> 
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
            <scope>runtime</scope>
        </dependency>
    </dependencies>

2. 项目目录结构

sprboot
│
└─src
	├─main/java/com/lkj/sprboot
	│		├─config
	│		├─controller
	│		├─service
	│		├─dao
	│		├─pojo
	│	    └─App.java
	└─main/resource
	 		├─mapper
			├─static
	 		├─templates
	 		├─outerproperties.properties
			└─application.yml

3. 配置文件

SpringBoot支持两种格式的配置文件:application.properties 、application.yml

SpringBoot会从四个位置读取配置文件,且配置文件的优先级依次降低,:

  • file:./config :项目的根目录的config

  • file:./ :项目的根目录

  • classpath:./config : resource/config文件夹目录

  • classpath:./ :resource文件夹目录

    注:上述四个位置中的所有配置文件都会被加载,但是高优先级的配置会覆盖低优先级的配置,并且多个配置文件中的配置会形成互补配置

配置项目启动端口


	server:
	  port: 8081  #在8081的端口上运行项目
	  
	  # 配置项目的上下文路径:localhost:8081/sprboot,不配置时默认为 /
	  servlet:
	    context-path: /sprboot 
	    

Spring 基础配置

	
	spring:
	  # 配置数据源,自动加载数据库连接池
	  datasource:
	    username: root
	    password: root
	    # 时区为GMT+8,其中`+`需要转义为`%2B`
	    url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
	  # thymeleaf模板引擎不使用缓存
	  thymeleaf:
	    cache: false
	  # 高版本的springboot与之不一样,使用的是data:format:
	  mvc:
	    # controller的入参时间格式配置,对应格式的字符串才能转化为date对象
	    date-format: yyyy-MM-dd
	  # 返回结果有时间数据时配置的时间格式
	  jackson:
	    date-format: yyyy-MM-dd
	    # 时区默认为格林尼治时间,+8是中国时区
	    time-zone: GMT+8
	    # 如果返回的结果字段为null就不返回给前端
	    default-property-inclusion: non_null
	    

多个环境下选择不同的配置文件

在多个环境下可能有多个版本的配置文件:application-dev.yml 、application-prod.yml 、application-test.yml,通过配置或者启动命令加载对应的配置文件。


	(application.yml)
	
	# 选择使用哪个配置文件,就激活哪个文件
	# 也可以在启动jar包时添加参数:--spring.profiles.active=dev来指定要加载的配置文件,可以使用此命令搭建分别使用不同端口的项目集群
	spring:
	  profiles:
	    active: dev   # 表明使用application-dev.yml文件
	    
	# 也可以使用文档块进行配置分割,使用 “---” 进行文档块的分界线
	# 使用时只需要将active的值改为对应的id即可
	---
	spring:
	  profiles: prod  # 生产环境
	server:
	  port: 8082
	  servlet:
	    context-path: /sprbootprod
	---
	spring:
	  profiles: test  # 测试环境
	server:
	  port: 8083
	  servlet:
	    context-path: /sprboottest
	    

日志配置

SpringBoot默认使用的Logback作为日志的记录工具,使用slf4j作为日志门面接口。


	logging:
	  level:
	    com.lkj.sprboot: debug  # 设置包级别的日志级别
	    ROOT: debug   # 设置全局的日志级别
	    org.springframework: error # 只打印spring包下的加载日志
	  file: mylog.log #配置日志输出的文件名,也可以配置文件名的绝对路径。
      path: E://logs  #配置日志的路径。如果没有配置logging.file,Spring Boot 将默认使用spring.log作为文件名。

4. 编写项目代码

编写启动类


package com.lkj.sprboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;

/**
   @MapperScan 扫描包中的dao接口
   
   在application.yml中需要指明mapper.xml文件的位置
   
   mybatis:
   configuration:
     map-underscore-to-camel-case: true   # 自动映射下划线为驼峰格式
   mapper-locations: classpath:mapper/*.xml
   
 **/
@SpringBootApplication
@MapperScan(value = {"com.lkj.dao"})
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

编写controller测试类


package com.lkj.sprboot.controller;

import com.lkj.sprboot.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.utils.ArrayList;

import java.util.Date;

@Controller
public class HelloController {
    @RequestMapping("hello")
    @ResponseBody
    public String hello(){
        return "hello";
    }

    @RequestMapping("curDate")
    @ResponseBody
    // 入参为yyyy-MM-dd时根据application.yml的配置自动转换为日期格式
    public Date curDate(Date date){ 
        return date;
    }

    @RequestMapping("index")
    public ModelAndView index(){
    	ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("list", new ArrayList<Project>());
		modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping("ajaxpost")
    @ResponseBody
    public User post(@RequestBody User user){ // 将json格式的数据封装成pojo
        System.out.println(user);
        return user;
    }
}

前端访问代码


// alljs.js文件

	// 通过jquery的异步请求发送json格式的数据
	$.ajax({
	    url: "/ajaxpost",
	    type: "POST",
	    // 发送json格式的数据需要设置消息格式
	    contentType: "application/json;charset=utf-8",
	    // 发送json时需要发送字符串,否则会将json对象转换为form表单格式数据
	    data: JSON.stringify({ "name" : "lili", "birthday" : "1997-03-09" }),
	    // 返回结果时建议返回的数据格式
	    dataType : "json",
	    success :function(result){
	        $("#na").html(result.name);
	        $("#pa").html(result.age);
	    }
	})


<!--前端index.html界面-->
<!DOCTYPE html>
<!-- 添加thymeleaf的命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入css文件 -->
    <link rel="stylesheet" type="text/css" th:href="@{/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/css/allcss.css}">
    <!-- 引入js脚本 -->
    <script type="text/javascript" th:src="@{/js/jquery-3.4.1.min.js}"></script>
    <script type="text/javascript" th:src="@{/js/alljs.js}"></script>
</head>
<body>
<div class="container center-vert">
    <div class="row center-block">
        <div class="col-lg-4 col-lg-offset-4">
            <table class="table table-striped">
                <tr >
                    <td><label for="na">姓名:</label><span id="na"></span></td>
                    <td><label for="na">年龄:</label><span id="pa"></span></td>
                </tr>
                <tr th:each="item:${list}">
                    <td>项目名:</td>
                    <td th:id="${item.id}"></td>
                </tr>
            </table>
        </div>
    </div>
</div>
</body>
</html>

在thymeleaf的模板中需要编写js脚本并且需要从model中获取值时可以使用 th:inline=“javascript” 内联js代码。


<script type="text/javascript" th:inline="javascript">
		
		// 获取每个project对应的名字
		[[${list}]].forEach(function(item){
			transferName(item.projectId,item.id);
		})
		
		// 转换projectid为projectname
		function transferName(projectId,id){

			var td = $("#"+id+"");
			var formdata = new FormData();
			formdata.append("projectId",projectId);
			// 从后端查询项目名并修改table的数据
			$.ajax({
				url : '/getPN',
				type : 'post',
				data : formdata,
				dataType : 'json',
				contentType : false, 
				processData : false,
				success : function(result) {
					if (result.code == 200) {
						//成功返回,设置项目名称
						td.html(result.projectName);
					} else {
						//状态失败
						alert("加载异常")
					}
				}
			})
		}
	</script>
	

5. @Value的使用

 application.yml中配置的变量值
 
 server:
   port: 8081
 address:
   beijing
   shagnhai
 jwt:
   name: lkj
   address:
     - beijing
     - shanghai

建立配置类从外部配置文件注入值 @PropertySource


	package com.lkj.sprboot.config;
	
	import org.springframework.beans.factory.annotation.Value;
	import org.springframework.context.annotation.PropertySource;
	import org.springframework.stereotype.Component;
	
	@Component
	// @PropertySource会将指定的配置文件中的变量注入到自己的属性中去,属性名要一一对应
	@PropertySource("outerproperties.properties") //加载外部配置
	public class OuterPropertiesConfig {
	
	    @Value("${hello}")
	    private String hello;
	
	    public void setHello(String hello) {
	        this.hello = hello;
	    }
	    public String getHello() {
	        return hello;
	    }
	}

建立配置类从application.yml中获取一组有前缀的值

	package com.lkj.sprboot.config;
	
	import org.springframework.boot.context.properties.ConfigurationProperties;
	import org.springframework.context.annotation.Configuration;
	import org.springframework.stereotype.Component;
	
	import java.util.List;
	
	@Component
	// @ConfiturationProperties 会将配置文件中指定前缀的属性自动注入到相应的类属性中
	@ConfigurationProperties(prefix = "jwt")
	public class PropertiesConfig {
	
	    private String name;
	
	    private List<String> address;
	
	    public void setName(String name) {
	        this.name = name;
	    }
	    public void setAddress(List<String> address) {
	        this.address = address;
	    }
	    public String getName() {
	        return name;
	    }
	    public List<String> getAddress() {
	        return address;
	    }
	}

Spring Boot Configuration Annotation Processor not configured 问题解决

使用@ConfigurationProperties注解后,idea会报Spring Boot Configuration Annotation Processor not configured问题

原因:没有配置 Spring Boot配置注解执行器,注解执行器配置后,当定义的类中已经使用@ConfigurationProperties注解修饰后,在配置文件中对前缀进行赋值时,application.yml 可以提供该类字段的自动提示。pom文件中加入以下依赖解决:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

从配置文件中直接读取值


 	@Value("${address}")
    private List<String> address;

    @Value("${server.port}")
    private Integer port;
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值