SpringBoot(五):@ConfigurationProperties配置参数绑定

在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;
}

备注:上边注解@[email protected]@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;

@[email protected]@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")

原文地址:https://www.cnblogs.com/yy3b2007com/p/8735367.html

时间: 2024-08-25 05:33:30

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

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

SpringMVC中的参数绑定还是蛮重要的,所以单独开一篇文章来讲解.本文所有案例代码的编写均建立在前文SpringMVC学习(四)——Spring.MyBatis和SpringMVC的整合的案例基础之上,因此希望读者能仔细阅读这篇文章. 默认支持的数据类型 现在有这样一个需求:打开商品编辑页面,展示商品信息.这是我对这个需求的分析:编辑商品信息,需要根据商品id查询商品信息,然后展示到页面.我这里假设请求的url为/itemEdit.action,由于我想要根据商品id查询商品信息,所以需要传

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

一.@Value方式 1.我的配置文件:application-dev.yml # 自定义项目配置 startproject: pro1: 11 pro2: 11 pro3: 11 pro4: 11 lists: - '1' - '2' - '3' maps: key1: 1 key2: 2 key3: 3 2.我的Java Bean /** * @author zhangboqing * @date 2018/9/18 */ @Data @Configuration public class

SpringBoot五步配置Mybatis

第一步:Maven里面添加mybatis的引用jar包: <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <depen

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

高级参数绑定 现在进入SpringMVC高级参数绑定的学习,本文所有案例代码的编写均建立在前文SpringMVC学习(五)——SpringMVC的参数绑定的案例基础之上,因此希望读者能仔细阅读这篇文章. 绑定数组 现有这样一个需求:在商品列表页面选中多个商品,然后删除之.下面是我对该需求的分析:此功能要求商品列表页面中的每个商品前有一个checkbook(复选框),选中多个商品后点击删除按钮把商品id传递给Controller,根据商品id批量删除商品信息. 首先将itemList.jsp页面改

SpringMVC详解(五)------参数绑定

参数绑定,简单来说就是客户端发送请求,而请求中包含一些数据,那么这些数据怎么到达 Controller ?这在实际项目开发中也是用到的最多的,那么 SpringMVC 的参数绑定是怎么实现的呢?下面我们来详细的讲解. 1.SpringMVC 参数绑定 在 SpringMVC 中,提交请求的数据是通过方法形参来接收的.从客户端请求的 key/value 数据,经过参数绑定,将 key/value 数据绑定到 Controller 的形参上,然后在 Controller 就可以直接使用该形参. 这里

五、参数绑定

1.SpringMVC 参数绑定 在 SpringMVC 中,提交请求的数据是通过方法形参来接收的.从客户端请求的 key/value 数据,经过参数绑定,将 key/value 数据绑定到 Controller 的形参上,然后在 Controller 就可以直接使用该形参. 这里涉及到参数绑定组件,那么什么是参数组件,这里可以先理解为将请求的数据转换为我们需要的数据称为参数绑定组件,也就是参数绑定转换器.SpringMVC 内置了很多参数转换器,只有在极少数情况下需要我们自定义参数转换器. 回

elasticsearch-query-builder, 一款可以基于配置化以及参数绑定的ES语句构造神器

前言 在这里,我想向大家推荐一个我自己开发的项目,也就是elasticsearch-query-builder,这个项目目前在github上已经开源,有兴趣的朋友可以去fork或者star,你的star就是对我最大的鼓励.同时,本项目长期维护和更新,我也接受并且很高兴有小伙伴向本项目pull request,或者协同开发,有兴趣的同学可以给我发邮件. elasticsearch-query-builder是一个非常方便构造elasticsearch(后面简称ES) DSL 查询语句的工具包,在e

面试题: SpringBoot 的自动配置原理及定制starter

3.Spring Boot 的自动配置原理 package com.mmall; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] ar

WebAPI路由、参数绑定

? 一.测试Web API a)测试Web API可以用来检测请求和返回数据是否正常,可以使用Fiddler.Postman等工具.以Fiddler为例,这是一个http协议调试代理工具,它能够记录客户端和服务器之间的所有 HTTP请求,可以针对特定的HTTP请求,分析请求数据.设置断点.调试web应用.修改请求的数据,甚至可以修改服务器返回的数据. b)Fiddler会默认捕获所有进程的通信,可以在All Processes中Hide All然后在Composer-Parsed选项卡选择需要捕