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结果 运行成功