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: -1datasource: 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()); }}
注意:如果使用@Value注解注入属性值,配置文件中的名称和代码中的名称必须要保持一致,否则会报错。