配置高级
configrationProperties注入
configrationProperties注入
案例演示 - 自己开发的组件bean绑定
创建新模块(非web)
新建ServerConfig.java
package com.taotao.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* create by 刘鸿涛
* 2022/5/20 12:32
*/
@SuppressWarnings({"all"})
@Component
@Data
@ConfigurationProperties(prefix = "servers")
public class ServerConfig {
private String ipAddress;
private int port;
private long timeout;
}
编辑Springboot13ConfigurationApplication.java
package com.taotao;
import com.taotao.config.ServerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import javax.xml.ws.Service;
@SpringBootApplication
public class Springboot13ConfigurationApplication {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Springboot13ConfigurationApplication.class, args);
ServerConfig bean = ctx.getBean(ServerConfig.class);
System.out.println(bean);
}
}
编辑application.yml
servers:
ipAddress: 192.168.0.1
port: 2345
timeout: -1
测试运行
案例演示 - 给第三方的bean绑定属性
configrationProperties注入
编辑Springboot13ConfigurationApplication.java
package com.taotao;
import com.alibaba.druid.pool.DruidDataSource;
import com.taotao.config.ServerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Springboot13ConfigurationApplication {
@Bean
@ConfigurationProperties(prefix = "datasource")
public DruidDataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
// ds.setDriverClassName("com.mysql.jdbc.Driver");
return ds;
}
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Springboot13ConfigurationApplication.class, args);
ServerConfig bean = ctx.getBean(ServerConfig.class);
System.out.println(bean);
DruidDataSource ds = ctx.getBean(DruidDataSource.class);
System.out.println(ds.getDriverClassName());
}
}
编辑application.yml
servers:
ipAddress: 192.168.0.1
port: 2345
timeout: -1
datasource:
driverClassName: com.mysql.jdbc.Driver456
测试运行
小结
解除注释警告
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
宽松绑定
书写格式
所谓的宽松绑定就是configrationProperties注入的书写规范并不严格
什么大小写,下划线、中划线、springboot都可以忽略