您的位置:首页 > 编程语言 > Java开发

Springboot快速入门(一)

2020-08-19 21:17 1726 查看

话说自己写java也有一段时间, 要说java快速开发, 首选的就是springboot, 给开发人员省去了很多的配置逻辑和tomcat启动和配置的烦恼, 如果大家是刚接触java, 还是不推荐大家直接上手学这个, 还是先去学习一下tomcat的启动和配置, 学习一下spring的一些基本知识和severlet的基本操作再来看这个吧.今天就把自己总结的springboot教教分享出来, 欢迎大家多多评论吧.

1. Spring Boot简介

Spring boot由pivotal团队(一家大数据公司)提供的全新框架, 具体设计的目的是用来简化新Spring应用的初始搭建一些开发过程, 该框架使用了特定的方式来进行配置, 从而使用开发人员不在需要定义复杂的配置, 通过这种方式, Springboot致力于在蓬勃发展的快速应用开发领域的领导者

简单来说, springBoot可以简化spring应用程序的开发, 是我们不在需要Spring配置文件及web.xml文件

说的更加简单一些, spring就是把内置在原来我们的springMVC的项目中的tomcat封装在了springboot中, 让我简化了开发工作.

1.1 Spring boot工程创建

  • 创建一个spring boot工程


  • 增加一个controller
package com.abc.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @ClassName SomeController
* @Description TODO
* @Author lingxiangxiang
* @Date 3:36 PM
* @Version 1.0
**/
@RestController
public class SomeController {

@RequestMapping("/some")
public String someHandle() {
return "hello spring Boot world";
}
}
  • 启动程序
  • 启动Application.java程序, 访问url如下图所示:

  • 打包
    可以使用idea编辑器中的maven配置中, 直接先点击clean, 然后点击package
    或者使用下面的命令
    mvn clean package
  • 在服务器上运行
    java -jar 01-primary-0.0.1-SNAPSHOT.jar

1.2 SpringBoot配置文件

1.2.1 编辑器

Spring Boot的主配置文件是src/main/resources 中默认创建的spring.properties文件. 该文件打开后是没有自动提示功能的. 此时可以打开Project Structure窗口, 在Modules中选中没有自动提示的功能, 添加以后, 就回有自动提示的功能, 包括后面的yml文件也会有自动提示功能



1.2.2 yml 文件

Spring Boot的主配置文件也可使用application.yml文件, yml, 也可以写成yaml.

在开发之初YAML的本意是Yet Anothre Markup Language(仍然是一种标记语言). 后来为了强调这种语言是以数据为中心, 而不是以标记为中心, 所以将YAML解释为 Yaml Ain't markup Language, 它是直观的能够被电脑识别的数据序列化格式, 是一个可读性高并且容易被人阅读, 容易和脚本语言交互, 并用来表达多级资源序列的编程语言

yml与properties文件的主要区别主要是对于多级属性, 即key的显示方式不同. yml文件在输入时, 只需要按照.的方式输出key即可, 输入完毕后回车即可出现了如下形式. 该形式要求冒号后和值之间有一个空格. 不同界别的属性值要求有两个空格缩进

需要注意,很多脚本中的空格都是作为无效字符出现的,但 yml 脚本则是作为有效字符出现的,必须要保证空格的数量。

server:
port: 9000
compression:
enabled: true
min-response-size: 2048

tomcat:
uri-encoding: utf-8

在演示时需要注意,application.properties 与 application.yml 这两个文件只能有一个。要求文件名必须为 application。所以,此时可以将 application.properties 文件重命名为其它名字即可。

1.3 Actuator 监控器

Actuator'æktʃʊˌeɪtə是 Spring Boot 提供的一个可插拔模块,用于对工程进行监控。其通过不同的监控终端实现不同的监控功能。其功能与 Dubbo 的监控中心类似,不同的是,Dubbo 的监控中心是需要专门部署的,而 Spring Boot 的 Actuator 是存在于每一个工程中的

1.3.1 基本环境搭建

  1. maven配置信息
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. 修改配置文件
server:
port: 9000
compression:
enabled: true
min-response-size: 2048

tomcat:
uri-encoding: utf-8

management:
server:
port: 9999
servlet:
context-path: /xxx
#      Actuator 监控的端口号和上下文路劲
endpoint:
endpoints:
web:
base-path: /base
#      指定监控终端的基本路劲, 默认为actuator
  1. 终端健康监测

1.3.2 添加info信息

  1. 添加修改配置文件
    info:
    company:
    name: abc
    url: http://www.abc.com
    addr: Beijing China
    auth:
    name: ajing2
    dep: develepment
    project:
    groupid: sdf
    artifactid: dfd
    version: 1.0.1
    name: 01-promary
  2. 测试

1.3.3 开放其他监控终端

默认情况下,Actuator 仅开放了 health 与 info 两个监控终端,但其还有很多终端可用,不过,需要手工开放

  1. 修改配置文件

application.properties

#开放所有监控终端, 默认只开启了health和info监控终端, 在yml中*为特殊字符, 需要使用双引号括起来
management.endpoints.web.exposure.include=*

application.yml

management:
server:
port: 9999
servlet:
context-path: /xxx
#      Actuator 监控的端口号和上下文路劲
endpoint:
endpoints:
web:
#      指定监控终端的基本路劲, 默认为actuator
base-path: /base
jmx:
exposure:
include: '*'
#        特殊字符需要引号

1.3.4 常用的监控终端

在百度搜索“springboot actuator”即可找到如下表格。全部都是get方法

1.3.5 单独关闭某些监控终端

修改配置文件

application.properties

management.endpoints.web.exposure.exclude=env, beans

application.yml

management:
server:
port: 9999
servlet:
context-path: /xxx
#      Actuator 监控的端口号和上下文路劲
endpoint:
endpoints:
web:
#      指定监控终端的基本路劲, 默认为actuator
base-path: /base
jmx:
exposure:
#        特殊字符需要引号
include: '*'
exclude: ['evn', 'beans']

2. Spring Boot自定义异常页面

对于 404、405、500 等异常状态,服务器会给出默认的异常页面,而这些异常页面一般 都是英文的,且非常不友好。我们可以通过简单的方式使用自定义异常页面,并将默认状态 码页面进行替换。

直接在前面程序上修改即可,无需创建新的工程。

2.1 定义目录

在 src/main/resources 目录下再定义新的目录 public/error,必须是这个目录名称。

2.2 定义异常页面

在 error 目录中定义异常页面。这些异常页面的名称必须为相应的状态码,扩展名为 html。

500.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8">
<title>500</title>
</head>
<body>
this is 500 error.
</body>
</html>

404.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8">
<title></title>
</head>
<body>
this is 404 error.
</body>
</html>

2.3 访问效果

修改如下代码

public class SomeController {

@RequestMapping("/some")
public String someHandle() {
int i = 3 / 0;
return "hello spring Boot world";
}
}


3. 单元测试

3.1 定义接口和实现类

package com.abc.service;

public interface SomeService {
void doSome();
}

注意,实现类上要添加@Service 注解,以交给 Spring 容器来管理。

实现类1:

package com.abc.service;

import org.springframework.stereotype.Service;

/**
* @ClassName SomeServiceImpl
* @Description TODO
* @Author lingxiangxiang
* @Date 9:37 AM
* @Version 1.0
**/
@Service
public class SomeServiceImpl implements SomeService{

@Override
public void doSome() {
System.out.println("SomeServiceImpl的doSome()");
}
}

实现类2:

package com.abc.service;

import org.springframework.stereotype.Service;

/**
* @ClassName OtherServiceImpl
* @Description TODO
* @Author lingxiangxiang
* @Date 9:39 AM
* @Version 1.0
**/
@Service
public class OtherServiceImpl implements SomeService {
@Override
public void doSome() {
System.out.println("OtherServiceImpl的doSome()");
}
}

3.2 测试类

package com.abc;

import com.abc.service.SomeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
// 若接口只有一个实现类, 则可以使用byType方式自动注入, 但现在存在两个实现类, 只能使用byName方式自动注入
@Autowired
@Qualifier("someServiceImpl")
private SomeService someService;

@Autowired
@Qualifier("otherServiceImpl")
private SomeService otherService;

@Test
public void contextLoads() {
someService.doSome();
otherService.doSome();
}

}

4. 多环境选择

  1. 相同代码运行在不同环境
    在开发应用时,通常同一套程序会被运行在多个不同的环境,例如,开发、测试、生产 环境等。每个环境的数据库地址、服务器端口号等配置都会不同。若在不同环境下运行时将 配置文件修改为不同内容,那么,这种做法不仅非常繁琐,而且很容易发生错误。

此时就需要定义出不同的配置信息,在不同的环境中选择不同的配置。

  1. 不同环境执行不同实现类
    在开发应用时,有时不同的环境,需要运行的接口的实现类也是不同的。例如,若要开 发一个具有短信发送功能的应用,开发环境中要执行的 send()方法仅需调用短信模拟器即可, 而生产环境中要执行的 send()则需要调用短信运营商所提供的短信发送接口。

此时就需要开发两个相关接口的实现类去实现 send()方法,然后在不同的环境中自动选 择不同的实现类去执行。

4.1 多配置文件的实现方式

在src/main/resources中在定义两个配置文件, 分别对应开发环境, 测试环境, 线上环境

[root@localhost ~]# ls -lhtr
total 32
-rw-r--r--  1 lingjing  staff     1B Jun 11 10:22 application-test.properties
-rw-r--r--  1 lingjing  staff     1B Jun 11 10:22 application-prod.properties
-rw-r--r--  1 lingjing  staff     1B Jun 11 10:22 application-dev.properties

application-dev.properties

server.port=8888

application-test.properties

server.port=8000

application-prod.properties

server.port=9999

application.properties

# 指定使用dev模式的配置文件
spring.profiles.active=dev

在 Spring Boot 中多环境配置文件名需要满足 application-{profile}.properties 的格式,其 中{profile}为对应的环境标识,例如,

  • application-dev.properties:开发环境
  • application-test.properties:测试环境
  • application-prod.properties:生产环境

至于哪个配置文件会被加载,则需要在 application.properties 文件中通过 spring.profiles.active 属性来设置,其值对应{profile}值。例如,spring.profiles.active=test 就会 加载 application-test.properties 配置文件内容。

在生产环境下,application.properties 中一般配置通用内容,并设置 spring.profiles.active 属性的值为 dev,即,直接指定要使用的配置文件为开发时的配置文件,而对于其它环境的 选择,一般是通过命令行方式去激活。配置文件 application-{profile}.properties 中则配置各个 环境的不同内容。

4.2 单配置文件的实现方式(不推荐)

这种实现方式只能使用 application.yml 文件,使用 application.properties 文件好像文件

本身就会出错。

将原有的配置文件全部删除,然后定义 application.yml 文件。需要注意的是,这三部分

之间是由三个减号(-)分隔的,必须是三个。而这三部分充当着之前的三个配置文件

spring:
profiles:
active:
- dev

---
spring:
profiles: dev

server:
prot: 8888
servlet:
context-path: /ddd

---
spring:
profiles:: pro

server:
port: 9999
servlet:
context-path: /ppp

5. 读取配置文件内容

5.1 读取住配置文件的属性

在@Value 注解中通过${ }符号可以读取指定的属性值。
application.properties

student.name = ajing

增加如下controller

package com.abc.multienv.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
* @ClassName SomeController
* @Description TODO
* @Author lingxiangxiang
* @Date 3:18 PM
* @Version 1.0
**/
@RestController
@RequestMapping("/test")
public class SomeController {
// 在@Value 注解中通过${ }符号可以读取指定的属性值。
@Value("${student.name}")
private String name;

@RequestMapping("/some")
public @ResponseBody String someHandle() {
return name;
}
}

结果:

curl http://127.0.0.1:8888/test/some
ajing

5.2 读取自定义配置文件的属性

一般情况下,主配置文件中存放系统中定义好的属性设置,而自定义属性一般会写入自定义的配置文件中。也就是说,Java 代码除了可以读取主配置文件中的属性外,还可以读取指定配置文件中的属性,可以通过@PropertySource 注解加载指定的配置文件。

spring boot 官网给出说明,@PropertySource 注解不能加载 yml 文件。所以其建议自定义配置文件就使用属性文件。

在src/main/resources目录中则增加myapp.properties

student.name = ajing

修改controller代码如下:

若属性的值存在中文,则需要添加 encoding 属性。

package com.abc.multienv.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
* @ClassName SomeController
* @Description TODO
* @Author lingxiangxiang
* @Date 3:18 PM
* @Version 1.0
**/
@RestController
@RequestMapping("/test")
@PropertySource(value = "classpath:myapp.properties", encoding = "utf-8")
public class SomeController {

@Value("${student.name}")
private String name;

@RequestMapping("/some")
public @ResponseBody String someHandle() {
return name;
}
}

5.3 读取对象属性

application.properties

student.name = ajing
student.age = 23
studnet.score = 93.5

实力类:

注解@ConfigurationProperties 注解需要以下依赖。

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

说明:

  • @ProertySource用于指定要读取的配置文件
  • @ConfigurationProperties用于指定要读取配置文件中的对象属性,即指定要读取的配置文件属性的前辍
  • @Component表示当前从配置文件读取来的对象,由Spring容器创建
  • 要保证类的属性名要与配置文件中的对象属性名相同
package com.abc.multienv.entry;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
* @ClassName Student
* @Description TODO
* @Author lingxiangxiang
* @Date 3:47 PM
* @Version 1.0
**/
@Component
@PropertySource("classpath:myapp.properties")
@ConfigurationProperties("student")
public class Student {
private String name;
private int age;
private double score;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public double getScore() {
return score;
}

public void setScore(double score) {
this.score = score;
}
}

修改controller类

package com.abc.multienv.controller;

import com.abc.multienv.entry.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
* @ClassName SomeController
* @Description TODO
* @Author lingxiangxiang
* @Date 3:18 PM
* @Version 1.0
**/
@RestController
@RequestMapping("/test")
public class SomeController {

@Autowired
private Student student;

@RequestMapping("/some")
public @ResponseBody String someHandle() {
System.out.println("student = " + student);
return student.getName();
}
}

5.4 读取List<String>属性

country.cities[0]=beijing
country.cities[1]=shanghai
country.cities[2]=shanxi

其余的和读取对象的一致

5.5 读取List<Object>属性

group.students[0].name=zhangsan
group.students[1].age=23
group.students[2].score=95.5

group.students[0].name=lisi
group.students[1].age=24
group.students[2].score=98.5
@Component
@PropertySource("classpath:myapp.properties")
@ConfigurationProperties("group")
public class Group {
private List<Student> students;
}

如果你觉得我写的不错, 就点个赞吧,点赞是一种态度.如果你想跟我多交流, 或者给我投稿, 也非常支持, 但只支持原创啊: 本人公众号stormling

欢迎来撩我! 欢迎大家留言!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: