三、Springboot基础配置

1、定制Banner

Spring Boot项目在启动的时候会有一个默认的启动图案,我们可以把这个图案修改为自己想要的。
首先创建一个banner.txt文件
通过网站http://www.network-science.de/ascii/一键生成ASCII图案,然后将自己的图案黏贴到banner.txt文件中,再放到src/main/resources目录下。

然后在主程序中设置banner

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

@SpringBootApplication
public class Springbootdemo1Application {

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

		SpringApplication app = new SpringApplication(Springbootdemo1Application.class);
		//开启自定义图案
		app.setBannerMode(Banner.Mode.CONSOLE);
		//关闭自定义图案
		//app.setBannerMode(Banner.Mode.OFF);
		app.run(args);
	}
}

比如输入mrbird生成图案后复制到banner.txt,启动项目,eclipse控制台输出如下:
在这里插入图片描述

2、配置文件

Springboot默认会使用一个全局的配置文件,配置文件名称是固定的:

  1. application.properties
  2. application.yml

配置文件的作用:
修改Springboot自动配置的默认值。

2.1、properties配置文件

在项目中,很多时候需要把配置写在properties里,部署的时候也需要切换不同的环境来选择正确的配置的参数,也有时候需要将mq redis等第三方配置新建一个properties文件在项目中引用。

2.1.1、properties的写法

server.port:8081
person.name:zhangsan
person.age:14

2.2、YAML配置文件

2.2.1、YAML是什么 ?

yml是YAML(YAML Ain’t Markup Language)语言的文件,以数据为中心,比json、xml等更适合做配置文件。
YAML A Markup Language:是一个标记语言
YAML isn’t Markup Language:不是一个标记语言

2.2.2、YAML配置语法

YAML基本语法:

  1. 使用缩进表示层级关系
  2. 缩进时不允许使用Tab键,只允许使用空格
  3. 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  4. 大小写敏感
  5. 冒号之后如果有值,那么冒号和值之间至少有一个空格,不能紧贴着
server:
  port: 8081

YAML支持的三种数据结构的写法

1.字面量:
单个的、不可再分的值,比如数字、字符串、布尔

  name: "张三"
  age: 14

注意:
“”:双引号,不会转义字符串里面的特殊字符
‘’:单引号,会转义特殊字符

2.对象:

person:
  name: "张三"
  age: 14

行内写法:

person: { name: "张三", age: 14}

3.数组:list、map
用-值表示数组中的一个元素

pets: 
  - dog
  - pig

行内写法:

pets: {dog,pig}

3、配置文件注入

3.1、@Value注入值

Spring Boot允许我们在application.properties下自定义一些属性,比如:

person.name:zhangsan
person.age:14

新建一个 Person类

@Component
public class Person {
    @Value("${person.name}")//application.properties中对应的值
    private String name;

    @Value("#{2*30}")//可以填写表达式
    private  int age;

    @Value("长沙")//可以注入普通字符串、数字等
    private String address;

    //省略getter和setter
}

编写HelloController,注入该Bean:

import com.example.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloContrller {
    @Autowired
    private Person person;

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World!"+person.getName()+","+person.getAge()+","+person.getAddress();
    }
}

启动项目,访问http://localhost:8080/hello,页面显示如下:
在这里插入图片描述

3.2、@ConfigurationProperties注入值

在属性非常多的情况下,也可以定义一个和配置文件对应的Bean,通过注解@ConfigurationProperties(prefix=“person”)指明了属性的通用前缀,通用前缀加属性名和配置文件的属性名一一对应。

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private  int age;
    private String address;

    //省略getter和setter
}

controller类不变,运行结果如下:
在这里插入图片描述

3.3、@Value获取值和@ConfigurationProperties获取值的区别

@Value@ConfigurationProperties
功能一个个绑定批量注入配置文件中的属性
松散绑定不支持支持
SpELl支持不支持
JSR303不支持支持
复杂类型封装不支持支持

配置文件yml还是properties他们都能获取到值:
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某一个值,使用@Value;
如果说,我们专门编写了一个JavaBean来和配置文件进行映射,我们就使用@ConfigurationProperties;

3.4、@PropertySource & @ImportResource & @Bean

3.4.1、@PropertySource 注解

作用 :加载指定的配置文件;

除了可以在application.properties里配置属性,我们还可以自定义一个配置文件。在src/main/resources目录下新建一个test.properties

test.name:test
test.age:1
test.address:广州

修改person类为

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

@Component
@ConfigurationProperties(prefix = "test")
@PropertySource("classpath:test.properties")
@Validated //校验
public class Person {
	@Email  //进行校验是否为邮箱
    private String name;
    private  int age;
    private String address;

    //省略getter和setter
@ConfigurationProperties(prefix = "test") 引入配置文件中的test的属性。
@PropertySource("classpath:test.properties")引入test配置文件。

如果前置一样可以统一配置

@ConfigurationProperties(prefix ="spring.wnagnian",locations = "classpath:config/xxx.properties")  

3.4.2、@ImportResource 注解

**作用:**导入Spring的配置文件,让配置文件生效;

创建一个实例:
第一、在service包下新建一个helloService类

package com.example.service;

public class HelloService {

}

第二、在 resource目录下面新建beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="com.example.service.HelloService"></bean>
</beans>

第三、在src/test/java/com/example/Springbootdemo1ApplicationTests.java下测试是否能直接获取helloSerivce

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

@SpringBootTest
class Springbootdemo1ApplicationTests {

	@Autowired
	ApplicationContext ioc;

	@Test
	public void testHelloService(){
		String s = "helloService";
		Boolean b = ioc.containsBean(s);
		System.out.println(b);
	}

	@Test
	void contextLoads() {
	}

}

第四、运行结果
在这里插入图片描述
结论:
Springboot里面没有Spring的配置文件,我们自己编写的配置文件,Springboot不能自动识别;

解决方法:
想让Spring的配置文件生效,加载进来,需要将**@ImportResource**标注在一个配置类上。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:beans.xml")
public class Springbootdemo1Application {

	public static void main(String[] args) {

		SpringApplication.run(Springbootdemo1Application.class, args);

	}
}

运行结果:
在这里插入图片描述

3.4.3、@Bean 注解

通过@importResource注解可以将xml中的bean注入,但是写法并不推荐。

Springboot推荐使用给容器中添加组件的方式实现注入Bean
1、创建一个Spring配置类
2、使用@Bean给容器中添加组件

import com.example.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Configuration:指明当前类是一个配置类,就是用来替代之前的Spring配置文件
 * 在配置文件中用<bean></bean>标签添加组件
 */
@Configuration
public class MyAppConfig {
   //将方法的返回值添加到容器中,容器中这个组件默认的ID就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器中添加组件了");
        return new HelloService();
    }
}

去test中运行,结果如下:

在这里插入图片描述

4、问题解决

4.1、springboot配置注解处理器没有找到问题

在这里插入图片描述
配置@ConfigurationProperties,IDEA 提示,springboot配置注解处理器没有找到,解决方案:

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

4.2、解决properties配置文件中打印中文乱码问题

使用IDEA工具遇到从properties配置文件中读取属性值遇到中文乱码的问题,是因为java文件设置的是UTF8编码格式,而properties不是造成的,解决办法是:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值