SpringBoot(一) 配置参数的绑定
在 SpringMVC 或其他 SSH 框架中,如果我们要实现一个配置参数的加载,需要使用代码实现读取properties文件等操作,或者需要使用其他写死的代码属性如 @value(name="username") 等配置。
SpringBoot极大的简化了这些流程,且可以将一个个的配置项转化为面向对象的数据实体对象,为开发工作带来的极大的便利,消除了配置项在项目中遍地开花的情况。
在 SpringBoot 中,参数绑定可以大致分为三个场景:
- 自定义配置参数绑定
- 第三方组件类的配置参数绑定
- 配置参数绑定启动参数
自定义配置参数绑定
此时,配置键值 可以来自项目内的配置文件如src/resources/application.properties, 或者来自各种配置中心如apollo。
例子
配置键值
db.username="root"
db.password="123456"
db.url="jdbc:mysql:///xxxxxxxxx"
db.driverClassName="com.mysql.jdbc.Driver"-
# db.driver_class_name="com.mysql.jdbc.Driver"
# db.driver-class-name="com.mysql.jdbc.Driver"
这里边的不区分大小写:db.driverClassName
可以写成:db.driver_class_name=xx
可以写成:db.driver-class-name=xx
创建自定义配置参数类
package com.app.config;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "db")
@Getter
@Setter
@ToString
public class MySQLConfig {
private String username;
private String password;
private String url;
private String driverClassName;
}
第三方组件类的配置参数绑定
自定义配置参数类不变。如上。
在入口类中注册三方组件中参数配置类
package com.app;
import app.config.MySQLConfig;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import java.util.Arrays;
@ComponentScans({@ComponentScan("com.app")})
@EnableAutoConfiguration
public class App {
@Bean
@ConfigurationProperties(prefix = "db")
public MySQLConfig mySQLConfig() {
return new MySQLConfig();
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
配置参数绑定启动参数
打包项目为jar包,进入jar包生成目录执行:java -jar jar包名称 --db.username=root --db.password=12345678 --db.url=jdbc:mysql:///mydb --db.driver=com.mysql.jdbc.Driver
正文到此结束
- 本文标签: Spring Spring Boot
- 版权声明: 本站原创文章,于2021年03月11日由风杨发布,转载请注明出处
热门推荐
相关文章
广告是为了更好的提供数据服务