@ConfigurationProperties 注解使用

参考

@ConfigurationProperties 注解使用姿势,这一篇就够了

使用@ConfigurationProperties注解的要点

  • 引入依赖spring-boot-configuration-processor

  • 被注解的类是被注册到了Spring容器中的Bean。

    方式一:@Component等组件注解和@ComponentScan组合,将组件注入Spring容器成为Bean。

    方式二:@EnableConfigurationProperties({KeyWordConfig.class})注解。

  • 被注解的属性有set方法。

  • 使用@ConfigurationProperties注解和@Value注解

  • yml中键如果有特殊字符,可以使用引号括起来,如果有特殊字符注意转义。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

@ConfigurationProperties注解实战

java代码配置springboot静态资源目录

参考mybatis-plus的crown项目

server:
port: 80
mozq:
# resource-map对应属性为resourceMap,连字符被去掉,连字符后面的首字母变大写了。
resource-map:
[/file/**]: "file:D:/00/00/"
[/img/**]: "file:D:/00/02/"
package com.mozq.boot.swagger01.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.LinkedHashMap; @Data
@ConfigurationProperties(prefix = MozqProperties.MOZQ_PREFIX)
public class MozqProperties {
public static final String MOZQ_PREFIX = "mozq";
private LinkedHashMap<String, String> resourceMap;
}
package com.mozq.boot.swagger01.config;

import com.mozq.boot.swagger01.properties.MozqProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.io.File; @Configuration
@EnableConfigurationProperties({MozqProperties.class})
public class MozqConfig implements WebMvcConfigurer { /*
这里注入了mozqProperties,但是不清楚原理,因为使用的是@EnableConfigurationProperties({MozqProperties.class})
MozqProperties对象并不是Spring中的bean。不能用注解直接注入。
*/
private MozqProperties mozqProperties;
public static final String USER_DIR = "user.dir"; public MozqConfig(MozqProperties mozqProperties){
this.mozqProperties = mozqProperties;
} @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
mozqProperties.getResourceMap().forEach((k,v)->{
// 因为直接使用"/file/**"会被过滤掉特殊字符,所以加上了中括号"[/file/**]",使用的时候要去除掉。
String key = k.substring(1, k.length() - 1);
registry.addResourceHandler(key).addResourceLocations(v);
System.out.println(key + " " + v);
});
registry.addResourceHandler("/**").addResourceLocations("file:" + System.getProperty(USER_DIR) + File.separator);
System.out.println(System.getProperty(USER_DIR));
} }

user.dir

package com.mozq.boot.swagger01.demo;

import com.mozq.boot.swagger01.config.MozqConfig;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.io.File; @RestController
public class DemoController {
/**
* springboot中"user.dir"属性得到的是jar包执行时,jar包所在的目录的磁盘路径,末尾不带文件分隔符。
* 如:jar包被放在"D:\Adobe",则 System.getProperty("user.dir")得到的磁盘路径就是"D:\Adobe"
* @return
*/
@RequestMapping("/userDir")
public String userDir(){
String userDir = System.getProperty(MozqConfig.USER_DIR) + File.separator;
return userDir;
} @RequestMapping("/realPath")
public String realPath(HttpServletRequest request){
String realPath = request.getServletContext().getRealPath("");
return realPath;
}
}
package com.mozq.freemarker.freemarker01.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@ConfigurationProperties(prefix = "wechat")
@Data
public class KeyWordConfig {
@Value("keywordxxx")
private String keyword;//注入常量值:keywordxxx @RequestMapping("/demo")
public String demo(){
System.out.println(keyword);
return keyword;
} @Value("${xhpay.front}")
private String xhpay; @RequestMapping("/demo2")
public String demo2(){
System.out.println(xhpay);
return xhpay;
} @Value("${///}")
private String demo;
@RequestMapping("/demo3")
public String demo3(){
System.out.println(demo);
return demo;
} @Value("${/account/tomcat:::\\\\}")
private String tomcat;
@RequestMapping("/demo4")
public String demo4(){
System.out.println(tomcat);
return tomcat;
} }
"///": changzhou
"/account/delete": authc
"/account/tomcat:::\\\\": "<html>\"
<head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /></head>
<body>
<p style='text-align:center;font-size: 48px;font-weight: bold;'>外卖前台联</p> <p style='text-align:center;font-size: 48px;font-weight: bold;'>餐桌号:123</p> <p style='Width:100%;text-align: left;font-weight: bold;'>支付时间:20191227143600320 </p>
<p style='Width:100%;text-align: left;font-weight: bold;'>支付状态:已支付</p>
</body>
</html>"

依赖和文件

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
##jwt配置
audience:
# 代表这个JWT的接收对象,存入audience
clientId: 098f6bcd4621d373cade4e832627b4f6
# 密钥, 经过Base64加密, 可自行替换
base64Secret: MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
# JWT的签发主体,存入issuer
name: restapiuser
# 过期时间,时间戳
expiresSecond: 172800

测试

package com.mozq.sb.jwt01.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Date; /**
* @description:
* @author: changzhou.xie@yuantiaokj.com
* @date: 2019/10/24 15:59
*/
@ConfigurationProperties("audience")
//@ConfigurationProperties(prefix = "audience", ignoreInvalidFields = true)
/*
@ConfigurationProperties 注解的bean必须先是spring中注册的bean。
如果不是则可以使用 @EnableConfigurationProperties(Audience.class) 来注册这个类。
或者使用@Component等组件将这个bean注册到spring中
@Import注解
*/
//@EnableConfigurationProperties(Audience.class)
@RestController
@Data
public class Audience {
String clientId;
String base64Secret;
String name;
String expiresSecond;
String password;//没有对应属性的则会是null。
/*
Failed to bind properties under 'audience' to com.mozq.sb.jwt01.config.Audience: Property: audience.clientid
Value: 098f6bcd4621d373cade4e832627b4f6
Origin: class path resource [application.yml]:6:13
Reason: No setter found for property: client-id
*/ @RequestMapping("/clientId")
public String clientId(){
System.out.println(clientId);
System.out.println(base64Secret);
System.out.println(name);
System.out.println(expiresSecond);
return clientId;
/* 运行结果:
098f6bcd4621d373cade4e832627b4f6
MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
restapiuser
172800
*/
}
}

@ConfigurationProperties

public @interface ConfigurationProperties {

	@AliasFor("prefix")
String value() default "";
/**
* The prefix of the properties that are valid to bind to this object. Synonym for
* {@link #value()}. A valid prefix is defined by one or more words separated with
* dots (e.g. {@code "acme.system.feature"}).
* @return the prefix of the properties to bind
*/
@AliasFor("value")
String prefix() default ""; /**
* Flag to indicate that when binding to this object invalid fields should be ignored.
* Invalid means invalid according to the binder that is used, and usually this means
* fields of the wrong type (or that cannot be coerced into the correct type).
* @return the flag value (default false)
* 是否忽略无效的字段,如果比如无法进行类型转换,则默认不忽略将报错。
*/
boolean ignoreInvalidFields() default false; /**
* Flag to indicate that when binding to this object unknown fields should be ignored.
* An unknown field could be a sign of a mistake in the Properties.
* @return the flag value (default true)
*/
boolean ignoreUnknownFields() default true; }

bugs

Failed to bind properties under 'audience.expires-second' to java.util.Date:

    Property: audience.expiressecond
Value: 172800
Origin: class path resource [application.yml]:12:18
Reason: No converter found capable of converting from type [java.lang.Integer] to type [java.util.Date]

@ConfigurationProperties 注解使用的更多相关文章

  1. springboot情操陶冶-@ConfigurationProperties注解解析

    承接前文springboot情操陶冶-@Configuration注解解析,本文将在前文的基础上阐述@ConfigurationProperties注解的使用 @ConfigurationProper ...

  2. @ConfigurationProperties注解取消location属性

    当我正在自学如何自定义properties配置文件,为了防止不必要的麻烦,重新创建了一个新的properties文件 fu.properties 然后在自定义的配置类中引入fu.properties/ ...

  3. 在Spring Boot中使用 @ConfigurationProperties 注解

    但 Spring Boot 提供了另一种方式 ,能够根据类型校验和管理application中的bean. 这里会介绍如何使用@ConfigurationProperties.继续使用mail做例子. ...

  4. SpringBoot自定义属性配置以及@ConfigurationProperties注解与@Value注解区别

    我们可以在application.properties中配置自定义的属性值,为了获取这些值,我们可以使用spring提供的@value注解,还可以使用springboot提供的@Configurati ...

  5. 在Spring Boot中使用 @ConfigurationProperties 注解, @EnableConfigurationProperties

    但 Spring Boot 提供了另一种方式 ,能够根据类型校验和管理application中的bean. 这里会介绍如何使用@ConfigurationProperties.继续使用mail做例子. ...

  6. Spring Boot 2 实践记录之 使用 ConfigurationProperties 注解将配置属性匹配至配置类的属性

    在 Spring Boot 2 实践记录之 条件装配 一文中,曾经使用 Condition 类的 ConditionContext 参数获取了配置文件中的配置属性.但那是因为 Spring 提供了将上 ...

  7. springboot之使用@ConfigurationProperties注解

    springboot之使用@ConfigurationProperties注解 代码已经上传至github https://github.com/gittorlight/springboot-exam ...

  8. @ConfigurationProperties注解对数据的自动封装

    @ConfigurationProperties注解对数据的自动封装 @ConfigurationProperties可以对基本数据类型实现自动封装,可以封装格式为yyyy/MM/dd的日期 测试代码 ...

  9. @ConfigurationProperties 注解使用姿势,这一篇就够了

    在编写项目代码时,我们要求更灵活的配置,更好的模块化整合.在 Spring Boot 项目中,为满足以上要求,我们将大量的参数配置在 application.properties 或 applicat ...

  10. Spring Boot中@ConfigurationProperties注解实现原理源码解析

    0. 开源项目推荐 Pepper Metrics是我与同事开发的一个开源工具(https://github.com/zrbcool/pepper-metrics),其通过收集jedis/mybatis ...

随机推荐

  1. 图像检索——VLAD

    今天主要回顾一下关于图像检索中VLAD(Vector of Aggragate Locally Descriptor)算法,免得时间一长都忘记了.关于源码有时间就整理整理. 一.简介 虽然现在深度学习 ...

  2. Spring Cloud Alibaba Sentinel对Feign的支持

    Spring Cloud Alibaba Sentinel 除了对 RestTemplate 做了支持,同样对于 Feign 也做了支持,如果我们要从 Hystrix 切换到 Sentinel 是非常 ...

  3. QDialog 设置成圆角

    void paintEvent(QPaintEvent *event) { Q_UNUSED(event); QBitmap bmp(this->size()); bmp.fill(); QPa ...

  4. JAVA基础系列:反射

    1. 定义 在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法:这 种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制. ...

  5. umi+dva+antd新建项目

    首先全局安装dva+umiumi:npm install -g umidva:npm install -g dva-cli 通过脚手架创建项目 一: mkdir myapp && cd ...

  6. Java-100天知识进阶-JVM内存-知识铺(三)

    知识铺: 致力于打造轻知识点,持续更新每次的知识点较少,阅读不累.不占太多时间,不停的来唤醒你记忆深处的知识点. Java内存模型(JMM) JVM内存模式是JVM的内存分区 Java内存模式是一种虚 ...

  7. laravel报错:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' (SQL: insert into `cart` (`uid`, `gid`, `gname`, `price`) values (3, 21, 夏季日系复古工装短袖衬衫男士印花潮流宽松五分

    原因:要操作的数据表id没有设置自增,导致出现id为0的情况 解决方法:给该数据表的id字段设置自增

  8. 【10】Nginx:后面有无 / 的区别

    写在前面的话 在 nginx 中,我们很多时候都有一个疑问,在 proxy_pass 或者 root 或者 location 后面需不需要加上 /,加和不加有啥区别. root  / alias 后面 ...

  9. 在进行机器学习建模时,为什么需要验证集(validation set)?

    在进行机器学习建模时,为什么需要评估集(validation set)? 笔者最近有一篇文章被拒了,其中有一位审稿人提到论文中的一个问题:”应该在验证集上面调整参数,而不是在测试集“.笔者有些不明白为 ...

  10. TEXT_CONVERT_XLS_TO_SAP 错误排查

    转自:https://blog.csdn.net/ityangjia/article/details/88827308 本文链接:https://blog.csdn.net/ityangjia/art ...