Spring Boot的类型安全配置

一 点睛

使用@Value注入每个配置,在实际使用上会显得很麻烦,因为我们的配置通常会有成百上千,如果通过这种方式,需要@Value注入很多次。

Spring Boot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,从而实现类型安全配置。

二 实战

1 新建一个Spring Boot项目。

2 在src/main/resources路径下新建配置文件teacher.properties

teacher.name=cakin24
teacher.age=36

3 编写类型安全的Bean

package com.wisely.ch6_2_3.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
//加载properties文件内的配置,通过prefix属性指定properties的配置前缀
//通过locations指定配置文件的位置
@ConfigurationProperties(prefix = "teacher",locations = {"classpath:teacher.properties"})
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;
    }
}

4 编写主类

package com.wisely.ch6_2_3;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wisely.ch6_2_3.config.AuthorSettings;
@RestController
@SpringBootApplication
public class Ch623Application {
    
    @Autowired
    private AuthorSettings authorSettings; //可以用@Autowired直接注入该配置
    
    @RequestMapping("/")
    public String index(){
        return "author name is "+ authorSettings.getName()+" and author age is "+authorSettings.getAge();
    }

    public static void main(String[] args) {
        SpringApplication.run(Ch623Application.class, args);
    }
}

三 运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值