1.记录springboot踩坑

1.使用application.yml配置文件
按教程用的是springboot1.5.9
但是idea自动的是根据2.2以后的给予默认填充。

配置文件值注入

  1. 先在src中写出Person Dog类

  2. 配置application.yml文件

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2017/12/12
    maps: {k1: v1,k2: 12}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 12
  1. javaBean:

    ConfigurationProperties:本类属性和配置文件中的配置属性进行绑定。

    prefix = “person”:配置文件中person下面的所有属性进行一一映射

    @Component:只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      
 *
 * 
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

我们可以导入配置文件处理器,以后编写配置就有提示了

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

测试时,利用自带的test里的java文件。
测试时出问题了,无法调用出配置好的信息,返回null,并且不报错
解决:必须import org.junit.Test(不知道为什么),自动import的junit什么api.test不好用。

package com.example.springboot02config;
import com.example.springboot02config.bean.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import  org.springframework.test.context.junit4.SpringRunner;

/**
 * springboot单元测试。可以在测试期间很方便的类似编码一样进行自动注入等容器的功能。
 */
@RunWith(SpringRunner.class)
@SpringBootTest
 public class SpringBoot02ConfigApplicationTests {
    @Autowired
	Person person;
	@Test
	public void contextLoads() {
		System.out.println(person);
	}

}

Spring Boot 2.2 之前的测试类
package com.example.demo1;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests {

@Test
public void contextLoads() {
}

}
Spring Boot 2.2 之后的测试类
package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

@Test
void contextLoads() {
}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值