springboot松散绑定

springboot松散绑定

什么是松散绑定,松散绑定是springboot在使用 @EnableConfigurationProperties 注解里面提出来的,也就是说在application.xml文件中,可以不那么严格的去命名变量名,比如说ipaddress可以在配置文件中有多种出线形势,但是在代码里面还是要以驼峰命名。

主要看ipaddress这个松散绑定

application.yml文件

servers:
  ipAddress: 192.168.0.1  
  ipaddress: 192.168.0.1  
  ip_Address: 192.168.0.1
  ip-address: 192.168.0.1
  port: 1234
  timeout: -1

datasource:
  driver-class-name: com.alibaba.druid.proxy.DruidDriver

核心代码

ipAddress: 192.168.0.1  //驼峰命名
ipaddress: 192.168.0.1  // 
ip_Address: 192.168.0.1  // 下划线命名
ip-address: 192.168.0.1 // -线命名

ServerConfig配置类

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

//@Component
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
    private String ipAddress;
    private int port;
    private int timeout;


}

springboot启动类

import com.alibaba.druid.pool.DruidDataSource;
import com.bubaiwantong.config.ServerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableConfigurationProperties(ServerConfig.class)
public class Springboot13ConfigurationApplication {

    @Bean
    @ConfigurationProperties(prefix = "datasource")
    public DruidDataSource dataSource(){
        DruidDataSource ds = new DruidDataSource();
        return ds;
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Springboot13ConfigurationApplication.class, args);
        ServerConfig bean = context.getBean(ServerConfig.class);
        System.out.println(bean);
        DruidDataSource dataSource = context.getBean(DruidDataSource.class);
        System.out.println(dataSource.getDriverClassName());
    }

}

image-20220412142323095

注意:如果使用@Value注解注入属性值,配置文件中的名称和代码中的名称必须要保持一致,否则会报错。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JavaGPT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值