Inject #Value to a Path variable directly - java

I want to inject Path variable directly without converting it from string like this:
#Value("${screenshot.path}")
private Path path;
property file:
screenshot.path=D:\Projects\myproject\screenshots
Error:
Unsatisfied dependency expressed through field 'path'; nested
exception is org.springframework.beans.TypeMismatchException: Failed
to convert value of type 'java.lang.String' to required type
'java.nio.file.Path'; nested exception is
java.lang.IllegalArgumentException: Failed to retrieve file for class
path resource [D:/Projects/myproject/screenshots]
Is there a way to do that without injecting String and then doing Paths.get?

My mistake, it does everything automatically, just fixed path format like this:
screenshot.path=D:\\Projects\\myproject\\screenshots

Related

Spring Boot - update data

I have a little problem.
I try update in repository one column.
Repository
#Modifying
#Query("UPDATE Conversation conversation SET conversation.friend = ?1 WHERE conversation.id = ?2")
fun setConversationInfoById(friend: Boolean, id: UUID): List<Conversation>
Service
fun addDeleteFriend(conversation: Conversation) {
val openedConversation = db.findByIdOrNull(conversation.id)
if (openedConversation == null) db.save(conversation)
else db.setConversationInfoById(openedConversation.friend, openedConversation.id)
}
Controler
#PostMapping("/friend", consumes = [MediaType.APPLICATION_JSON_VALUE])
#ResponseBody
fun friend(#RequestBody conversation: Conversation) = service.addDeleteFriend(conversation)
It's about the flag - boolean whos will change status column "friend".
When I'm starting BE the console shows me this error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with
name 'conversationController' defined in file [####]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name
'conversationService' defined in file [####]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'conversationRepository' defined in com.###.backend.repository.ConversationRepository defined in
#EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration:
Invocation of init method failed; nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for
public abstract java.util.List com.###.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
Reason: Failed to create query for method public abstract java.util.List
com.##.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
No property 'setConversationInfoById' found for type 'Conversation'!; nested exception is
java.lang.IllegalArgumentException: Failed to create query for method public abstract
java.util.List com.###.backend.repository.ConversationRepository.setConversationInfoById(boolean,java.util.UUID)!
No property 'setConversationInfoById' found for type 'Conversation'!
I tried all option, but I don't know what is the problem ..
query method changes Conversation data by id, which is one data.
So it will be return one Conversation object.
try to change List to Conversation.
or, I don't know well, but quertymethod naming convention is exist, so try to check out.

test failed when i use #Value [duplicate]

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.

Spring org.springframework.beans.ConversionNotSupportedException exception

Could someone say why I am getting this exception ?
And how to solve the problem ?
If I understand correctly com.test.dao.CustomerDAO$$EnhancerByCGLIB$$ae49026e_3 class generated at runtime by spring.
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.test.dao.CustomerDAO$$EnhancerByCGLIB$$ae49026e_3' to required type 'com.test.dao.CustomerDAO'

Spring 3.2.4 can't convert String to Enum in <util:map.../> although 'key-type' is specified

I'm trying to define a map bean with Spring 3.2.4 with an Enum as the key type, this way:
<util:map id="myMapping" key-type="com.acme.MyEnum">
<entry key="ENUM1" value="value1" />
<entry key="ENUM2" value="value2" />
</util:map>
The MyEnum class is a trivial class:
public enum MyEnum
{
ENUM1,
ENUM2
}
When creating the application context, Spring throws this exception:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myMapping':
Error converting typed String value for bean property 'sourceMap';
nested exception is org.springframework.beans.ConversionNotSupportedException:
Failed to convert value of type 'java.lang.String' to required type
'com.acme.MyEnum'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type
[com.acme.MyEnum]: no matching editors or conversion strategy found
(formatted for better readbility)
I expected Spring to convert the String "ENUM1" to "MyEmum.ENUM1", because of the given key type
key-type="com.acme.MyEnum"
in the mapping bean declaration.
I know how to solve this by doing an alternate bean definition, using <entry>, using the full qualified class name of the enum etc... But I would like to build the defintion as described for easy readability.
Is this a known bug or a lack of understanding on my side?
Thanks a lot for your help!
You could try to use this strategy for string conversion.
public enum MyEnum
{
ENUM1("ENUM1"),
ENUM2("ENUM2")
}
Actually it seems correct how do you use utils-map, but may be the problem is elsewhere.
I don't know how do you inject the created myMapping bean. If you use #Autowired, it is a possible reason why you get this exception. You should use #Resource(name="myMapping") instead of #Autowired. See this ticket.
I have already test it and it works. If you want to see how, I created a sample project and pushed on github. Follow this link.
I hope it helps.

Java: how to make sense out of cryptic stack traces?

While trying to run a unit test, I get the following stack trace. I don't even know where to start looking (read my comment below).
Where should I start and what would you do to solve this?
(note that the following stack trace is basically how I get it from Eclipse, without any formatting or anything: just countless lines of about 120 chars each) [I only pasted the five lines where apparently the problem happens]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'acceptanceChain' defined in class path resource
[.../chain/connector/...xml]: Cannot resolve reference to bean 'xxxCommand' while setting constructor argument with key [0]; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxxCommand' defined in class path resource
[.../bl/chain/connector/....xml]: Cannot create inner bean 'yyyDTO#1d95da7' of type [yyyListDTO] while setting bean property 'yyyListDTO'; nested exception
is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'yyyListDTO#1d95da7' defined in class path resource
[zzz.xml]: Unsatisfied dependency expressed through constructor argument with index 0 of type [boolean]: Could not convert constructor argument value of type
[java.util.LinkedHashMap] to required type [boolean]: Failed to convert value of type [java.util.LinkedHashMap] to required type [boolean]; nested exception
is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.LinkedHashMap] to required type [boolean]: no matching editors or conversion
strategy found
Any help is very welcome.
Take the signifiant part of the message :
Error creating bean with name 'acceptanceChain' defined in class path resource
I guess the bean acceptanceChain can't be instanciated. Maybe because it has a boolean parameter in which one tries to inject a LinkedHashMap, as the following message states :
Failed to convert value of type [java.util.LinkedHashMap] to required type [boolean]

Categories