码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-04-08 00:14:37      阅读:706      评论:0      收藏:0      [点我收藏+]

标签:AC   nio   绑定   hot   style   sys   use   配置参数   map   

在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配置参数绑定

标签:AC   nio   绑定   hot   style   sys   use   配置参数   map   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!