SpringBoot中自定义配置类

本文介绍了在SpringBoot中自定义配置类的两种方法。第一种方法是使用@ConfigurationProperties注解并配合@Component,设置前缀,并确保提供get/set方法。配置项在application.properties中定义,可在其他Bean中直接注入。第二种方法则是不使用@Component,而是直接在根配置类中引入配置类。

SpringBoot中自定义配置类

1.方式一:

配置类标注:

  1. @ConfigurationProperties注解,可以设置前缀名
  2. @Component 将该类放入spring容器中
  3. 必须设定get/set方法

配置类:

@Component //将该Bean放入spring容器中
@ConfigurationProperties(prefix = "com.example")//指定该类为配置获取类,并指定前缀
public class MyConfig {
    private String name;
    private Integer age;
    //必须设置get set方法

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

application.properties中配置

com.example.age=20
com.example.name=xxx

使用:
在其他Bean中可以直接注入该Bean

@RestController
public class DemoController {
    @Autowired
    private MyConfig config;
    @GetMapping("/demo2")
    public String m2(){
        return config.getName();
    }

}

2.方式二

配置类:
不使用 @Component 将该类放入spring容器中,而是使用@EnableConfigurationProperties(MyConfig.class)在根配置类中引入


@ConfigurationProperties(prefix = "com.example")//指定该类为配置获取类,并指定前缀
public class MyConfig {
    private String name;
    private Integer age;
    //必须设置get set方法

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
@SpringBootApplication
@EnableConfigurationProperties(MyConfig.class) //引入自定义配置类
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class,args);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值