2.1 初学springboot全局配置文件

文章展示了如何在Springboot项目中使用application.properties配置文件设置属性,并通过@ConfigurationProperties注解将这些属性自动绑定到Person实体类中。Person类包含id、name、hobby、family等字段,并且能处理列表和映射类型的数据。在测试类中,使用@Autowired注解注入Person对象并打印,验证配置的正确性。
摘要由CSDN通过智能技术生成

1.application.properties(在resource目录下)

定义Springboot项目相关的属性

person.id=1
person.name=tom
person.hobby=play,read,sleep
person.family=father,mother
person.map.k1=v1
person.map.k2=v2
person.pet.type=dog
person.pet.name=kity

2.实体类person.java

package com.example.springboot1.domain;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.*;

@Component    // 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中
public class Person {

    private int id;            //id
    private String name;      //名称
    private List hobby;       //爱好
    private String[] family; //家庭成员
    private Map map;
    private Pet pet;          //宠物
}

其中

@Component    // 用于将Person类作为Bean注入到Spring容器中
@ConfigurationProperties(prefix = "person") // 将配置文件中以person开头的属性注入到该类中

@component注解作用是此前注入的属性值的person类对象作为bean组件放在spring容器中,只有这样他才能被@ConfigurationPerperties注解赋值。

3.为了验证可在test中输出测试

package com.example.springboot1;



import com.example.springboot1.domain.Person;
import com.example.springboot1.domain.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import javax.validation.constraints.Email;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter02ApplicationTests {
    @Autowired
    private Person person;


    @Test
    public void contextLoads() {
        System.out.println(person);
    }
}

@Autowire注解是将Person作为bean注入spring容器中

然后在contextload()中运行输出person。

4结果  运行成功

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值