乱码:

<!--配置 yml文件处理器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
完整代码:
Dog类
public class Dog {
String name;
int age;
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
person 类
Person 类
//将配置文件中的值映射到person中
//@ConfigurationProperties 告诉springboot将本类中的所有属性与配置文件中相关的属性配置
//这个组件是容器中的组件,才能提供功能加@Component注解
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
String name;
int age;
Date birth;
Map<String,Object> map;
Dog dog;
List list;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", birth=" + birth +
", map=" + map +
", dog=" + dog +
", list=" + list +
'}';
}
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 Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
properties 文件中的配置:
server.port=8081
person.name=sunchao
person.age=22
person.birth=2022/12/12
person.map.k1=k1
person.list=a,bc,c
person.dog.name=xiaogou
person.dog.age=2
测试:
package com.sunchao.demo;
import com.sunchao.demo.bean.Person;
import org.junit.jupiter.api.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;
@RunWith(SpringRunner.class)
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
本文介绍了如何在Springboot项目中配置properties文件,并将配置内容映射到对应的Java类,通过实例展示了Dog和Person类的使用,以及properties文件中的配置方式和测试方法。
508

被折叠的 条评论
为什么被折叠?



