在springmvc或其他ssh框架中如果我们要实现一个配置参数的加载,需要使用代码实现读取properties文件等操作,或者需要使用其他属性@value(name="username")等配置操作。但是在springboot中就比较简单操作:

1)自定义配置参数绑定:通过使用@ConfigurationProperties和@Component注解自定义参数配置类,之后程序启动时将自动加载application.properties配置文件中的对应的配置项;

2)第三方组件类的配置参数绑定:需要在springboot启动类内部把该参数配置类注册为一个Bean,同时注解@ConfigurationProperties就可以实现第三方组件配置参数加载;

3)配置参数绑定启动参数:无论是上边1)还是2)参数配置除了可以在application.properties中配置外,还可以绑定启动参数。

1)自定义配置参数绑定:

a)创建自定义配置参数类:

在app下新建包config,在app.config包下创建一个MySQLConfig.java:

package 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")
@Component
@Getter
@Setter
@ToString
public class MySQLConfig {
private String username;
private String password;
private String url;
private String driverClassName;
}

备注:上边注解@Getter@Setter@ToString的依赖包是lombok,需要在pom.xml添加配置:

        <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

c)在src/resources/application.properties中添加配置:

db.username="root"
db.password="123456"
db.url="jdbc:mysql:///mytestdb"
db.driverClassName="com.mysql.jdbc.Driver"

备注:这里边的不区分大小写:db.driverClassName

可以写成:db.driverclassname=xx

可以写成:db.driver_class_name=xx

也可以写成db_driver-class_Name=xx

d)将app.config包注解为启动入口监控的组件包:

package app;

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.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans; import java.util.Arrays; @ComponentScans({@ComponentScan("com.dx.controller"), @ComponentScan("app.config")})
@EnableAutoConfiguration
public class App {
public static void main(String[] args) {
System.out.println(Arrays.toString(args));
// 启动方式一:
SpringApplication.run(App.class, args); // 启动方式二:
// SpringApplication springApplication = new SpringApplication(App.class);
// springApplication.setBannerMode(Banner.Mode.OFF);
// springApplication.run(args); // 启动方式三:
// new SpringApplicationBuilder(App.class)
// .bannerMode(Banner.Mode.OFF)
// .build()
// .run(args);
}
}

e)新建测试接口类DataSourceTestController.java:

package com.dx.controller;

import app.config.MySQLConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
public class DataSourceTestController {
@Autowired
private MySQLConfig mySQLConfig; @RequestMapping("/dataSource")
@ResponseBody
public String dataSource() {
System.out.println(mySQLConfig);
return "dataSource";
}
}

f)运行app.App.java,在浏览器中访问http://localhost:8888/dataSource回车,查看打印信息:

MySQLConfig(username="root", password="123456", url="jdbc:mysql:///mytestdb", driverClassName="com.mysql.jdbc.Driver")

2)第三方组件类的配置参数绑定:

a)假设上边自定义参数配置类app.config.MySQLConfig.java为一个第三方参数配置类:

package app.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString; @Getter@Setter@ToString
public class MySQLConfig {
private String username;
private String password;
private String url;
private String driverClassName;
}

b)在入口类中注册三方组件中参数配置类:

package 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.dx.controller")})
@EnableAutoConfiguration
public class App {
@Bean
@ConfigurationProperties(prefix = "db")
public MySQLConfig mySQLConfig() {
return new MySQLConfig();
} public static void main(String[] args) {
System.out.println(Arrays.toString(args));
// 启动方式一:
SpringApplication.run(App.class, args); // 启动方式二:
// SpringApplication springApplication = new SpringApplication(App.class);
// springApplication.setBannerMode(Banner.Mode.OFF);
// springApplication.run(args); // 启动方式三:
// new SpringApplicationBuilder(App.class)
// .bannerMode(Banner.Mode.OFF)
// .build()
// .run(args);
}
}

c)测试:运行app.config.App.java,在浏览器中访问http://localhost:8888/dataSource,回车。查看打印信息:

MySQLConfig(username="root", password="123456", url="jdbc:mysql:///mytestdb", driverClassName="com.mysql.jdbc.Driver")

3)配置参数绑定启动参数:

打包项目为jar包,进入jar包生成目录执行:

java -jar jar包名称 --db.username=root --db.password=12345678 --db.url=jdbc:mysql:///mydb --db.driver=com.mysql.jdbc.Driver

执行后,访问地址http://localhost:8888/dataSource回车。此时,查看打印信息如下:

E:\Work\springboot\springboothelloword\target>java -jar springboot-helloword-1.0-SNAPSHOT.jar --db.username=root --db.password=12345678 --db.url=jdbc:mysql:///mydb --db.driver=com.mysql.jdbc.Driver
[--db.username=root, --db.password=12345678, --db.url=jdbc:mysql:///mydb, --db.driver=com.mysql.jdbc.Driver] _ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' | |
\ .-\__ `-` ___/-. /
___`. .' /--.--\ `. . __
."" '< `.___\_<|>_/___.' >'"".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
佛祖保佑 永无BUG
2018-04-07 22:38:39.210 INFO 10288 --- [ main] app.App : Started App in 4.387 seconds (JVM running for 5.763)
2018-04-07 22:38:46.759 INFO 10288 --- [nio-8888-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-04-07 22:38:46.761 INFO 10288 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-04-07 22:38:46.805 INFO 10288 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 44 ms
MySQLConfig(username=root, password=12345678, url=jdbc:mysql:///mydb, driverClassName="com.mysql.jdbc.Driver")

SpringBoot(五):@ConfigurationProperties配置参数绑定的更多相关文章

  1. 对MySQL性能影响较大的五类配置参数

    以下主要是对MySQL 性能影响关系紧密的五大配置参数的介绍. 一.      连接 连接通常来自Web 服务器,下面列出了一些与连接有关的参数,以及该如何设置它们. (一).             ...

  2. (转)SpringMVC学习(五)——SpringMVC的参数绑定

    http://blog.csdn.net/yerenyuan_pku/article/details/72511611 SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案 ...

  3. SpringBoot application.properties配置参数详情

    multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...

  4. 【Spring Boot】Spring Boot之自定义配置参数绑定到Java Bean

    一.@Value方式 1.我的配置文件:application-dev.yml # 自定义项目配置 startproject: pro1: pro2: pro3: pro4: lists: - ' - ...

  5. 开发笔记-19/10/28 -SpringBoot @Value 获取配置参数

    1. 在application.properties 定义参数 role.taskEvent :参数名称 4:值 ## ---------------------任务角色--------------- ...

  6. SpringBoot五步配置Mybatis

    第一步:Maven里面添加mybatis的引用jar包: <!--mybatis--> <dependency> <groupId>org.mybatis.spri ...

  7. 2. springboot加载配置参数顺序

    加载顺序依次是:1.jar的classes里面的application.properties 2.当前路径下config里面的application.properties 3.jar的classes里 ...

  8. SprimgMVC学习笔记(三)—— 参数绑定

    一.默认支持的参数类型 1.1 需求 打开商品编辑页面,展示商品信息. 1.2 需求分析 编辑商品信息,首先要显示商品详情 需要根据商品id查询商品信息,然后展示到页面. 请求的url:/itemEd ...

  9. (转)SpringMVC学习(六)——SpringMVC高级参数绑定与@RequestMapping注解

    http://blog.csdn.net/yerenyuan_pku/article/details/72511749 高级参数绑定 现在进入SpringMVC高级参数绑定的学习,本文所有案例代码的编 ...

随机推荐

  1. 20165226 预备作业3 Linux安装及学习

    20165226 预备作业3 Linux安装及学习 Linux安装 一.下载安装VirtualBox 1.首先在官网下载,点开基于VirtualBox虚拟机安装Ubuntu图文教程 找到版本进行下载安 ...

  2. 关于数据库的左,右,内,外连接,Union和Union all---------笔记

    1.左连接 select a.filed1,a.filed2,b.filed1 from a (左表) left join b(右表) on a.commonfiled = b.commonfiled ...

  3. Lucene-01:创建索引

    我们在D盘下建一个文件夹叫lucene,lucene内再建两个文件夹,一个叫example,一个叫index01.example文件夹下三个txt文件,a.txt内容为hello java,b.txt ...

  4. 【Linux】 linux中的进程信息相关的一些内容

    _ linux进程信息 ■ top top命令用于动态地查看系统的进程和其他一些资源的信息.开启top的时候可以加上-t <sec>来设置top更新的频率高低.进入top界面之后,可以输入 ...

  5. 爬虫(scrapy--豆瓣TOP250)

    # -*- coding: utf-8 -*- import scrapy from douban_top250.items import DoubanTop250Item class MovieSp ...

  6. 程序猿媛 九:Adroid zxing 二维码3.1集成(源码无删减)

    Adroid zxing 二维码3.1集成 声明:博文为原创,文章内容为,效果展示,思路阐述,及代码片段. 转载请保留原文出处“http://my.oschina.net/gluoyer/blog”, ...

  7. Java注解(3)-注解处理器(编译期|RetentionPolicy.SOURCE)

    注解的处理除了可以在运行时通过反射机制处理外,还可以在编译期进行处理.在编译期处理注解时,会处理到不再产生新的源文件为止,之后再对所有源文件进行编译. Java5中提供了apt工具来进行编译期的注解处 ...

  8. javaScript设计模式 -- 灵活的javaScript语言

    因为好长时间的懒惰和懈怠,好久没有更新文章了,从现在开始我会按时更新一些自己总结的一些知识,和研究的东西,希望能让大家从我这里学到一点点的知识. 本文参考了张荣铭的javascript设计模式一书,算 ...

  9. mysql数据库导入sql文件时提示“Error Code: 1153 - Got a packet bigger than 'max_allowed_packet' bytes”解决办法

    向mysql数据库中导入sql文件时,如果文件过大(几百M),会提示"Error Code: 1153 - Got a packet bigger than 'max_allowed_pac ...

  10. [福大软工] W班 第2次成绩排行榜

    作业链接 https://edu.cnblogs.com/campus/fzu/FZUSoftwareEngineering1715W/homework/866 评分细则 本次个人项目分数由三部分组成 ...