欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot自定义配置文件和类

程序员文章站 2022-05-01 23:26:26
...

自定义配置文件

SpringBoot自定义配置文件和类

id=3
name=王五


java 类使用

PropertySource 指定配置文件
@Value注入


@Configuration
@Component
@PropertySource( "classpath:student.properties")
public class Student {

    @Value("${id}")
    private int id;
    @Value("${name}")
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
                .add("id=" + id)
                .add("name='" + name + "'")
                .toString();
    }
}

测试

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Task01Appliction.class)
public class DemoTest01 {


    @Autowired
    private Student student;


    @Test
    public void testDemo02(){

        System.err.println(student);
    }
}

Student[id=3, name=‘王五’]

加上前缀

stu.id=3
stu.name=王五

java类上也加上前缀


@Component
@PropertySource( "classpath:student.properties")
@ConfigurationProperties(prefix = "stu")
public class Student {

//    @Value("${id}")
    private int id;
//    @Value("${name}")
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return new StringJoiner(", ", Student.class.getSimpleName() + "[", "]")
                .add("id=" + id)
                .add("name='" + name + "'")
                .toString();
    }
}