SpringBoot获取自定义配置

第一种方法@Value("${变量名称}")

示例如下:

 

 

 

 效果

 第二种 将自定义配置映射到对象

配置文件 application.properties

school.name=alibabaschool
school.website=www.alibaba.school.com

增加一个config的包 新增一个School类

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

@Component //讲此类给spring的容器管理
@ConfigurationProperties(prefix = "school")
public class School {
    private String name;
    private String website;

    public String getName() {
        return name;
    }

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

    public String getWebsite() {
        return website;
    }

    public void setWebsite(String website) {
        this.website = website;
    }
}

然后调用 注解@Autowired

@Controller
public class IndexController {
    @Autowired
    private School school;

    @RequestMapping(value = "say")
    public @ResponseBody String say(){
        return "hello,SpringBoot!" + "school的名字是:"+ school.getName() + "---school的网址是" + school.getWebsite();
    }
}

启动效果

 

解决告警的依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

 

posted @ 2022-04-20 22:37  羽毛球打的贼好  阅读(239)  评论(0)    收藏  举报