I am using sprin version 4.3.8.RELEASE. also i am using #Value to inject values from property file, if the properties are string that no problem, but if the property is Integer that is a problem (i know there is many questions about this i tried all the answers but the issue still exist)
The property is
CONNECTION.TIME.OUT=100000
First solution
#Value("${CONNECTION.TIME.OUT}")
protected Integer connectionTimeOut;
Ecxeption
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "${CONNECTION.TIME.OUT}"
Second solution
#Value("#{new Integer('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Exception
EL1003E: A problem occurred whilst attempting to construct an object of type 'Integer' using arguments '(java.lang.String)'
Third solution
#Value("#{new Integer.parseInteger('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Exception
EL1003E: A problem occurred whilst attempting to construct an object of type 'Integer' using arguments '(java.lang.String)'
any ideas why is that
To avoid such type of situation where the exception occurs due to un-availibilty of the property, Add default value in the tag. If property is not available then it will populate the default value
#Value("${CONNECTION.TIME.OUT:10}")
Your property file is probably not loaded properly.
When provided with no valid value for a property placeholder, Spring will automatically try to assign this value to the name of the #Value annotation. In your case, this:
#Value("#{new Integer('${CONNECTION.TIME.OUT}')}")
protected Integer connectionTimeOut;
Is interpreted as:
protected Integer connectionTimeOut = new Integer("${CONNECTION.TIME.OUT}");
Which, indeed, brings an error.
Try to either configure a PropertyPlaceholderConfigurer in your beans, or make sure that your property file is loaded properly in your classpath by your configuration. Something among the lines of:
<context:property-placeholder
ignore-unresolvable="true"
location="classpath:yourfile.properties" />
In your configuration file will help, in this case.
For #Value("${CONNECTION.TIME.OUT}") your error is java.lang.NumberFormatException: For input string: "${CONNECTION.TIME.OUT}". This means that expression was not processed resulting in Integer.parseInt("${CONNECTION.TIME.OUT}") which thrown the NumberFormatException.
Either there is no PropertyPlaceholderConfigurer bean registered in the Spring context and #Value annotations are not processed or there is no property CONNECTION.TIME.OUT defined.
Try removing single quotes worked ''. It worked for me.
#Value("#{new Integer(${CONNECTION.TIME.OUT})}")
Don't forget the "${}" around it! I kept looking at what should have been obvious and missing it.
Related
I'm having trouble setting null as a property value.
This is how the value is defined in YAML file:
my-property: null
This is how I inject it in code:
#Value("${my-property}")
private String myProperty;
For some reason, Spring keeps injecting an empty string ("") instead of null. Am I missing something or is this an error in Spring?
You can't, but this is not because YAML. YAML supports null as per:
Empty field in yaml
This is because of a Spring processor class, which turns "null" values into empty strings, see here:
https://github.com/spring-projects/spring-framework/issues/19986
Try to use instead of $ use this #.
Or try this #Value("${<my-property>}")
I had a similar use case, and had to go through quite a bit of trial and error.
The following two-step solution worked for me
Don't define my-property in the YAML file. This way Spring cannot (annoyingly) inject a stringified value like "" or "~" or "null", and will be forced to look for a default value.
Use #{null} as the default value. This is an SpEL expression that evaluates to null.
In your example, it will be
#Value("${my-property:#{null}}")
private String myProperty;
Be careful not to mess up with the curly brackets.
I am using Spring and Java for an application, and I want to use the #Value annotation to inject the value of the property, my use case is that I want first to check if that property exists as system property (so it takes priority), and otherwise default to a configuration property (existing in the properties file)
In the commented code you can see what I am trying to achieve, is that possible to default to something else that a simple string? If it is not, how can I achieve this?
//#Value("#{configProperties['local.datasource.username']}") THIS IS THE ORIGINAL CODE
//#Value("#{systemProperties['some.key'] ?: 'my default system property value'}") THIS IS HOW SPRING PROPOSE TO SET A DEFAULT VALUE
//#Value("#{systemProperties['some.key'] ?: #{configProperties['local.datasource.username']}}") THIS IS WHAT I WANT TO ACHIEVE, HOWEVER NOT COMPILING,
private String username;
What you are looking for are simple Property Palceholders.
While the Spring Expression Language supports the #{} syntax for rather complex expressions (ternary, calls, expressions, math), injecting property values and defaults is in most cases better done using a simple property placeholder ${value:defaultValue} approach:
#Property("${some.key:local.datasource.username}")
private String username;
Where some.key is being resolved (independent of its origin), and if that is null, Spring defaults to the value of local.datasource.username.
Please keep in mind, that even if some.key is present, Spring will throw an exception when it can't resolve your default property.
See also:
Spring Expression Language (SpEL) with #Value: dollar vs. hash ($ vs. #) and
A Quick Guide to Spring #Value
I'm already familiar with the base behavior of Spring's #Value annotation to set a field to the value of a project property like so:
Project's Property File
foo.bar=value
Project's Configuration Class
#Configuration
public class MyConfig {
#Value("${foo.bar}")
private String myValue;
}
However I'm trying to make a SpringBoot starter project with conditional configuration and would like to standardize the property names to something useful such as "com.mycompany.propertygroup.propertyname", but to ease transition and encourage adoption, I want to support the old property names for a time as well, and was thus wondering if there was some way to allow multiple property names to set the same field? For instance:
My Theoretical Starter's Config
#Configuration
public class MyConfig {
#Value("${com.mycompany.propertygroup.propertyname}" || "${oldconvention.property}")
private String myValue;
}
Project A's Property
oldconvention.property=value
Project B's Property
com.mycompany.propertygroup.propertyname=value
I can't seem to find any documentation or SO answers on whether or not this is possible and how to achieve it if so... So I'm wondering if it is possible, or if it's not, is there an alternative to the #Value annotation that can be used to achieve the same effect?
Edit to Clarify:
I would not want to keep track of multiple values so I do not need instruction on how to get multiple values... the objective is to consolidate into a SINGLE VALUE that which may have multiple names. In practice, it would only ever have one name-value per project that uses the starter... only in rare cases when someone perhaps forgot to delete the old property would each property name be used (and it would probably have the same value anyway). In such cases, the NEW CONVENTION NAME-VALUE WOULD BE THE ONLY ONE USED.
Update
While the SpEL expression answers provided works when both properties are present, the application context cannot load when only one of the property names is present. Example:
Updated Configuration Class
#Value("#{'${com.mycompany.propertygroup.propertyname}' != null ? '${com.mycompany.propertygroup.propertyname}' : '${oldconvention.propertyname}'}"
private String myProperty;
Updated Property File
com.mycompany.propertygroup.propertyname=somevalue
Error
Caused by: java.lang.IllegalArgumentException:
Could not resolve placeholder 'oldconvention.propertyname' in value
"#{'${com.mycompany.propertygroup.propertyname}' != null ? '${com.mycompany.propertygroup.propertyname}' : '${oldconvention.propertyname}'}"
Requiring both property names to be present defeats the purpose, which is to allow an implementing project to configure this starter using EITHER the old convention OR the new convention...
Another Update...
I've been playing around with the SpEL expression a bit, and I've got the conditional check working when the property is present and when it's not, but I'm having trouble with property resolution after the fact. I think the problem is because property defaults and complex SpEL expressions don't play nice together.
#Value("#{${com.mycompany.propertygroup.propertyname:null} != null ? '${com.mycompany.propertygroup.propertyname}' : '${oldconvention.propertyname}'}")
private String myProperty;
When my SpEL is written like the above, I get a cannot resolve property placeholder exception, meaning that both properties have to be present in order for the SpEL expression to evaluate. So I got to thinking, I could use the default property syntax that I've seen for resolving optional properties: #Value("${myoptionalproperty:defaultValue}")
So below is my attempt to combine the default property resolution with the SpEL expression:
#Value("#{${com.mycompany.propertygroup.propertyname:null} != null ? '${com.mycompany.propertygroup.propertyname:}' : '${oldconvention.propertyname:}'}")
private String myProperty;
When using the default property notation, I keep getting this error:
org.springframework.expression.spel.SpelParseException:
EL1041E: After parsing a valid expression, there is still more data in the expression: 'colon(:)'
and when I Googled that error, the popular answer was that properties had to be wrapped in single quotes so that they evaluate to a string... but they're already wrapped (except the first one.. I had to unwrap that one since I wanted that to evaluate to a literal null for the null check). So I'm thinking that defaults can't be used with properties when they're wrapped in a spell expression. In truth, I've only ever seen the default property set when a #Value annotation is set with just a pure property holder, and all properties I've seen used in a SpEL expression never had a default set.
You can use the following #Value annotation:
#Configuration
public class MyConfig {
#Value("#{'${com.mycompany.propertygroup.propertyname:${oldconvention.propertyname:}}'}")
private String myValue;
}
This #Value annotation uses com.mycompany.propertygroup.propertyname if it is provided and defaults to oldconvention.property if com.mycompany.propertygroup.propertyname is not provided. If neither is provided, the property is set to null. You can set this default to another value by replacing null with another desired value.
For more information, see the following:
Spring Expression Language (SpEL)
Spring Expression Language Guide
As an alternative, you can capture both values and do a selection before returning the value:
#Configuration
public class MyConfig {
#Value("${com.mycompany.propertygroup.propertyname:}")
private String newValue;
#Value("${oldconvention.propertyname:}")
private String oldValue;
public String getValue() {
if (newValue != null && !newValue.isEmpty()) {
// New value is provided
System.out.println("New Value: " + newValue);
return newValue;
}
else {
// Default to the old value
return oldValue;
}
}
}
Using SPEL is the best way to solve this. This should work
#Value("#{'${com.mycompany.propertygroup.propertyname}' != null ? '${com.mycompany.propertygroup.propertyname}' : '${oldconvention.property}'}")
private String myValue;
No that's not possible I believe but yes you can define property as comma separated. For example
com.mycompany.propertygroup.propertyname=value1,value2,value3
And instead of receiving a String you can annotate #Value over String[] like this:
#Value("#{'${com.mycompany.propertygroup.propertyname}'.split(',')}")
private String[] propertyNames;
Another way you can also store key and value as a comma-separated string in the property file and use #Value annotation you can map into Map, For example, you want group name as key and value as group details so in the property file you can store string like this
group.details.property= {'group1':'group1.details','group2':'group2.details'}
And you can annotate #Value as
#Value("#{${group.details.property}}")
private Map<String, String> groupMap;
I have a Struts 2 (JDK 1.7, Struts 2.2.1) application that contains a list of filtering criteria, stored as strings in a map.
Map< String, String > m_filters = new HashMap< String, String >();
public Map< String, String > getFilters() {
return m_filters;
}
I pass a URL formatted like this:
http://myserver.com/myapp/GenerateReport.action?reportID=Whatever&filters.fromDate=0&filters.toDate=2000000000&filters.FcsType=piv_cardholder_3kp&detailed=true
Even though the Map has both key & value types specified as String, attempting to get a value from this
Map< String, String > filters = getFilters();
String value = filters.get( "fromDate" );
causes this exception to be thrown:
java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String
I reproduced this in a unit test, and confirmed in a debugger that Struts 2 seems to be creating a String[1] instead of a String for each of the parameters. i.e. it is a length-1 string array with the only string being the expected value ("0" in this case).
My question is: Is this a bug in Struts2, or am I doing something incorrectly?
If it is a bug, is there a known workaround?
There are no issues if you follow Java bean conventions.
Here are some guidelines to resolve the issue:
This issue does not happen if you name the private member "filter" and provide only a getter for filter.
This issue does not happen if you provide a public setter (even if you use a different name for the private member such as m_filter) in addition to the getter
this issue only happens if you do not provide a setter and the property does not have the same name as the getter.
Long story short follow conventions. Above behaviour tested with Struts 2.3.4
What I'm guessing is happening: The getter allows for setting too (If there was only a setter you could only set one item in the map, well with the current parameter interceptor this is the case). The bean is inspected for the property to see how it should do type conversion probably first it looks for a setter failing that it looks at the action for a propterty of that name to determine the type failing that it will need to use the default. The default parameter type is a mapping of String to String[] and this is what you are seeing.
You're using the wrong notation. filters.fromDate would be the equivalent of getFilters().setFromDate(), which is not actually what you want. Dot notation is for JavaBeans.
Try using brackets, such as filters['fromDate'].
Refer to: http://struts.apache.org/2.2.1/docs/type-conversion.html#TypeConversion-RelationshiptoParameterNames.
Try this:
Object[] obj = (Object[]) filters.get( "fromDate" );
String value = (String)obj[0]);
It's not a bug you can consider it's a feature. Access RequestParameters
ParameterAware Interceptor
Let us suppose /http://localhost:8080/myApp/login.action?name=struts2&name=rocks
if you try to access the name parameter string[0] = struts2, string1=rocks
For example in mule-config.xml file, if we have
---Start
spring:bean id="objPool" class="org.apache.commons.pool.impl.GenericObjectPool"
spring:property name="whenExhaustedAction" value="#
{org.apache.commons.pool.impl.GenericObjectPool.WHEN_EXHAUSTED_GROW}"
---End
Here, WHEN_EXHAUSTED_GROW is public static final byte and its value is 2.
Now when I do mule -config mule-config.xml, I get following error
Error:
org.mule.api.lifecycle.InitialisationException: Initialisation Failure: Error creating bean with name 'videoRequestSAXParserObjectPool' defined in URL [file:/home/joshlabs/codebase/collider-server-tidal/src/main/resources/mule-config-pingback.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.lang.String] to required type [byte] for property 'whenExhaustedAction'; nested exception is java.lang.NumberFormatException: For input string: "{org.apache.commons.pool.impl.GenericObjectPool.WHEN_EXHAUSTED_GROW}"
Please help me how can I convert "byte" datatype to "String" datatype.
Thanks,
Prince
Mule 2.1.2 depends on Spring 2.5.6, which doesn't support Spring Expression Language (SpEL). In Spring 2, you'll need to use util:constant to read the WHEN_EXHAUSTED_GROW value and inject it.
You have an SpEL problem, not a Mule one.
When you type a class name, SpEL doesn't know if that is a class or not. So it's returning
"org.apache.commons.pool.impl.GenericObjectPool.WHEN_EXHAUSTED_GROW" as a string. You should use the T operator.
Try this :
#{T(org.apache.commons.pool.impl.GenericObjectPool).WHEN_EXHAUSTED_GROW}"