Springboot需要通过配置文件直接读取属性时,可以将其注入到实体类上面,两种方法:@ConfigurationProperties和@value

一、通过@ConfigurationProperties直接将配置文件整体关联

@Component:将当前bean注入到容器中,@Configuration等于xml配置bean文件

@ConfigurationProperties(prefix = "user"):从配置文件中找user开头的

@Component
@ConfigurationProperties(prefix = "user")
public class User {

    private int id;
    private String name;
    private String description;

    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;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

application.properties属性新增:

user.id=1
user.name=wuxi
user.description=学习springboot

controllar层:@Autowired 直接引用注入的User对象,写个简单的请求返回user对象

@RestController
public class UserControllar {

    @Autowired
    User user;

    @RequestMapping("/user")
    public User testUserProperties() {

        return user;
    }

}

 运行springboot ,浏览器访问:http://localhost:8080/user

可以看到属性已经绑定成功,不过里面出现乱码

我们把properties文件属性钩上红框的内容

重新编写application.properties中文内容,并重启,再次访问ok

二、使用@value进行绑定,需要一个个类的属性进行绑定,比较麻烦

修改User类注解:

@Component
//@ConfigurationProperties(prefix = "user")
public class User {

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

    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;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

一样可以获取

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐