@ConfigurationProperties 注解使用


@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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM