类型安全的配置

1、添加配置
author.name=张三
author.age=20
2、类型安全的Bean
package com.example.springboot.config;

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

@ConfigurationProperties(prefix = "author")
@Component
public class AuthorSettings {
    private String name;
    private Long age;

    public String getName() {
        return name;
    }

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

    public Long getAge() {
        return age;
    }

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

3、测试
package com.example.springboot.controller;

import com.example.springboot.config.AuthorSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestAuthor {

    @Autowired
    private AuthorSettings author;

    @RequestMapping("/")
    public String index() {
        return "author name is " + author.getName() + " and age is " + author.getAge();
    }

}

你可能感兴趣的:(类型安全的配置)