轻轻松松学习SpringBoot2:第六篇:Spring Boot获取properties属性和一个Bean关联

前两篇说了获取properties文件中的值,倘若这些值比较多,而且相关的一类元素能否有个更好的处理办法

答案是有的,Spring Boot如此优秀,对付这点渣渣道还是小菜一碟,采取bean的方式即可解决

一)新建配置文件,此处我们定义一个person.properties的文件,内容如下

person.name=木子
person.age=20
person.english_name=muzi

二)建立java Bean 文件, 此处我们定义一个Person类如下:

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:person.properties")
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;

    private String age;

    private String english_name;

    //按住alt+insert生成get和set


    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getEnglish_name() {
        return english_name;
    }

    public void setEnglish_name(String english_name) {
        this.english_name = english_name;
    }
}

注意:我这是Spring Boot 2.X版本,所以注解需要用到PropertySource和ConfigurationProperties两个注解

如果是Spring Boot1.5的则用ConfigurationProperties即可,使用prefix获取页面访问地址,locations获取配置文件

其中get,set方法自动生成,可以通过在Bean文件中右击,选择Genetate,有get和set即可,或者使用快捷键 Alt+insert

三)修改我们的主类DemoApplication代码,如下

    @Autowired
    private Person person;
    @RequestMapping(value = "/person",produces = "text/plain;charset=UTF-8")
    String index(){
        return "Hello Spring Boot!,the person's info :the name "+person.getName()+"   ,and the age is " +person.getAge()+"  the englishname is "+person.getEnglish_name();
    }

然后重启服务就能获取到我们想要的结果


ok!

猜你喜欢

转载自blog.csdn.net/stronglyh/article/details/80788237