In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail "Springboot @ Value injection boolean how to set the default value", the content is detailed, the steps are clear, and the details are handled properly. I hope this "Springboot @ Value injection boolean how to set the default value" article can help you solve your doubts.
@ Value injection boolean setting default value problem description
Read configuration files in Springboot
Test:
The business code is as follows
@ Value ("${test:true}") private boolean test
The error is as follows
Nested exception is org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type' boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value []
Analysis of problems
According to the error report, the main problem is that the value of test is of type String and cannot be converted to type boolean.
@ Value ("${test:true}") private String test
So I changed the receive type to see if the value obtained was true, and found that the test value was "" instead of the default value set.
Solution
The problem with error reporting is that as long as there is test in the configuration file: so the system defaults to "" instead of empty as I expected, so the default value is true.
Delete the test in the configuration file directly: start normally.
@ Value source code reading
I also roughly followed the source code in the process of troubleshooting the problem.
/ / org.springframework.beans.TypeConverterSupport#doConvert () private T doConvert (Object value, Class requiredType, MethodParameter methodParam, Field field) throws TypeMismatchException {try {return field! = null? This.typeConverterDelegate.convertIfNecessary (value, requiredType, field): this.typeConverterDelegate.convertIfNecessary (value, requiredType, methodParam);} catch (ConverterNotFoundException var6) {throw new ConversionNotSupportedException (value, requiredType, var6);} catch (ConversionException var7) {throw new TypeMismatchException (value, requiredType, var7);} catch (IllegalStateException var8) {throw new ConversionNotSupportedException (value, requiredType, var8) } catch (IllegalArgumentException var9) {/ / final exception throws throw new TypeMismatchException (value, requiredType, var9) from here;}}
The final assignment is in
/ / org.springframework.beans.TypeConverterDelegate#doConvertTextValue () private Object doConvertTextValue (Object oldValue, String newTextValue, PropertyEditor editor) {try {editor.setValue (oldValue);} catch (Exception var5) {if (logger.isDebugEnabled ()) {logger.debug ("PropertyEditor [" + editor.getClass (). GetName () + "] does not support setValue call", var5) }} / / found here that newTextValue is "" editor.setAsText (newTextValue); return editor.getValue ();}
Next is the specific code for how to convert the string true to boolean:
/ / org.springframework.beans.propertyeditors.CustomBooleanEditor#setAsText () public void setAsText (String text) throws IllegalArgumentException {String input = text! = null? Text.trim (): null; if (this.allowEmpty & &! StringUtils.hasLength (input)) {this.setValue ((Object) null);} else if (this.trueString! = null & & this.trueString.equalsIgnoreCase (input)) {this.setValue (Boolean.TRUE);} else if (this.falseString! = null & & this.falseString.equalsIgnoreCase (input)) {this.setValue (Boolean.FALSE) } else if (true! = null | |! "true" .equalsIgnoreCase (input) & &! "on" .equalsIgnoreCase (input) & &! "yes" .equalsIgnoreCase (input) &! "1" .equals (input)) {if (this.falseString! = null | |! "false" .equalsIgnoreCase (input) &! "off" .equalsIgnoreCase (input) & &! "no" .equalsIgnoreCase (input) & & ! "0" .equals (input) {throw new IllegalArgumentException ("Invalid boolean value [" + text + "]") } this.setValue (Boolean.FALSE);} else {this.setValue (Boolean.TRUE);}}
Using IDEA to find classes in tips:windows can use the shortcut key combination of ctrl + shift + alt + N to query, while the mac system is commond + O
Spring parsing @ Value
1. Initialize the PropertyPlaceholderHelper object
Protected String placeholderPrefix = "${" protected String placeholderSuffix = "}"; @ Nullable protected String valueSeparator = ":"; private static final Map wellKnownSimplePrefixes = new HashMap (4); static {wellKnownSimplePrefixes.put ("}", "{"); wellKnownSimplePrefixes.put ("]", "["); wellKnownSimplePrefixes.put (")", "(") } public PropertyPlaceholderHelper (String placeholderPrefix, String placeholderSuffix, @ Nullable String valueSeparator, boolean ignoreUnresolvablePlaceholders) {Assert.notNull (placeholderPrefix, "'placeholderPrefix' must not be null"); Assert.notNull (placeholderSuffix, "' placeholderSuffix' must not be null"); / / default ${this.placeholderPrefix = placeholderPrefix; / / default} this.placeholderSuffix = placeholderSuffix; String simplePrefixForSuffix = wellKnownSimplePrefixes.get (this.placeholderSuffix) / / if the current prefix is empty or does not match the definition, take the prefix if (simplePrefixForSuffix! = null & & this.placeholderPrefix.endsWith (simplePrefixForSuffix)) {this.simplePrefix = simplePrefixForSuffix;} else {this.simplePrefix = this.placeholderPrefix;} / / default: this.valueSeparator = valueSeparator; this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;}
2. Parse @ Value
Protected String parseStringValue (String value, PlaceholderResolver placeholderResolver, Set visitedPlaceholders) {StringBuilder result = new StringBuilder (value); / / whether the prefix is included, return the beginning of the first prefix index int startIndex = value.indexOf (this.placeholderPrefix); while (startIndex! =-1) {/ / find the index int endIndex = findPlaceholderEndIndex (result, startIndex) of the last suffix If (endIndex! =-1) {/ / remove the prefix and suffix and take out the string String placeholder = result.substring (startIndex + this.placeholderPrefix.length (), endIndex); String originalPlaceholder = placeholder If (! visitedPlaceholders.add (originalPlaceholder)) {throw new IllegalArgumentException ("Circular placeholder reference'" + originalPlaceholder + "'in property definitions") To determine whether there is a placeholder recursively, you can write ${acm.endpoint:$ {address.server.domain:}} placeholder = parseStringValue (placeholder, placeholderResolver, visitedPlaceholders); / / get the corresponding value String propVal = placeholderResolver.resolvePlaceholder (placeholder) according to key The / / value does not exist, but there is a delimiter if for the default value (propVal = = null & & this.valueSeparator! = null) {/ / to get the default index int separatorIndex = placeholder.indexOf (this.valueSeparator) If (separatorIndex! =-1) {/ / cut off the default string String actualPlaceholder = placeholder.substring (0, separatorIndex); / / cut out the default value String defaultValue = placeholder.substring (separatorIndex + this.valueSeparator.length ()) / / get the corresponding value propVal = placeholderResolver.resolvePlaceholder (actualPlaceholder) according to the new key; / / if the value does not exist, assign the default value to the current value if (propVal = = null) {propVal = defaultValue } / / if the current value is not NULL if (propVal! = null) {/ / Recursively get the value information with placeholder propVal = parseStringValue (propVal, placeholderResolver, visitedPlaceholders) / / replace placeholder result.replace (startIndex, endIndex + this.placeholderSuffix.length (), propVal); if (logger.isTraceEnabled ()) {logger.trace ("Resolved placeholder'" + placeholder + "'") } startIndex = result.indexOf (this.placeholderPrefix, startIndex + propVal.length ());} else if (this.ignoreUnresolvablePlaceholders) {/ / Proceed with unprocessed value. StartIndex = result.indexOf (this.placeholderPrefix, endIndex + this.placeholderSuffix.length ());} else {throw new IllegalArgumentException ("Could not resolve placeholder'" + placeholder + "'" + "in value\"+ value +"\ ");} visitedPlaceholders.remove (originalPlaceholder) } else {startIndex =-1;}} return result.toString () } after reading this, the article "how to set the default value for Springboot @ Value injection boolean" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.