error passing a value in a bean - java

I'm getting an error when passing an integer through spring.
<bean id="propConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/application.properties"/>
</bean>
<bean id="portListenerService" class="com.service.portListenerService" scope="prototype" lazy-init="true" parent="abstractService">
<property name="devicePort" value="${devicePort}"/>
</bean>
portListenerService.java:
#Required
public final void setDevicePort(Integer devicePort) {
this.devicePort= devicePort;
}
Is this the correct way to do this? Because I am getting an error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'portListenerService' defined in ServletContext resource [/WEB-INF/service-config.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 [int] for property 'devicePort'; nested exception is java.lang.IllegalArgumentException: Original must not be null
Even when I hardcode the port instead of pulling it from application.properties, I get the same error. Is some other problem amiss?

Could the devicePort related code be violating javabean spec - like in this discussion?

It may not have anything to do with type of field. Usually this happens when there is a problem with setters, make sure the setter exists with return type void and your fields must start with lower case letter and setter would obviously have camel case for property with 'set' as prefix.
for example; I had the same issue recently and find out that the one of the letter within the property had different case in setter.
<bean name="gateway" class="com.xxxx.yyyy.zzz.MyClass" init-method="init">
...
<property name="stateLogIntervalms" value="${mux.state.log.interval.ms}" />
...
</bean>
definition of property in my class for correct like following;
protected Long stateLogIntervalms;
However definition of setter for incorrect like this;
public void setStateLogIntervalMs(Long stateLogIntervalms) {
this.stateLogIntervalms = stateLogIntervalms;
}
you can notice that the second last letter 'M' is in different case than what I had in xml property and java class.
Happy Coding:)

Related

Cannot convert value type 'Configuration' to required type FreeMarkerConfigurationFactoryBean for property freeMarkerConfigurationFactoryBean

Getting below error while using free-marker template in spring:pls suggest.
applicationContext.xml:
Dependent bean:
<bean id="domainManager" class="DomainManager">
<property name="freeMarkerConfigurationFactoryBean" ref="freeMarkerConfigurationFactoryBean"/>
<property name="sampleFile" value="sampleFile.ftl" />
</bean>
Error:
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'freemarker.template.Configuration' to required type 'org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean' for property 'freeMarkerConfigurationFactoryBean'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'freemarker.template.Configuration' to required type 'org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean' for property 'freeMarkerConfigurationFactoryBean': no matching editors or conversion strategy found
No need to keep the freeMarkerConfigurationFactoryBean in dependent beans.And use below bean
Where ever we are using Reports keep below template class as autowired with that class.
#Autowired
Configuration freemarkerConfiguration;
freemarkerConfiguration.setClassForTemplateLoading(this.getClass(), CUSTOM_Constant.FREEMARKER_TEMP_LOCATION);
body = FreeMarkerTemplateUtils.processTemplateIntoString( freemarkerConfiguration.getTemplate(fmTemplateName),templateParams);

Error when constructing a spring bean of an object with one Enum, and then a vararg of enums

I have the following object and constructor:
public class Options {
public Options(Enum option, Enum... moreOptions) {
// My code...
}
public Enum build(String nameOfEnum) {
// Creates enum....
}
}
I'm trying to create a spring bean for it using the following xml, based off an answer to another stackoverflow question:
<bean id="myBean" class="com.mypackage.Options">
<constructor-arg value="#{Options.build('firstEnum')}" />
<constructor-arg>
<list>
<value>#{Options.build('secondEnum')}"</value>
<value>#{Options.build('thirdEnum')}"</value>
</list>
</constructor-arg>
<bean>
I just run into the following error, however:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name myBean defined in ServletContext resource [applicationContext.xml]: Unsatisfied dependency expressed through constructor argument with index 1 of type [java.lang.Enum[]]: Could not convert constructor argument value of type [java.util.ArrayList] to required type [[Ljava.lang.Enum;]: Failed to convert value of type 'java.util.ArrayList' to required type 'java.lang.Enum[]'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.lang.Enum]: no matching editors or conversion strategy found
I've tried some variations on my current spring config, like having all values in the list, or just creating each value on its own. None seem to work.
How do I correctly create my spring bean?

Spring Beans - how to wire null as a constructor arg?

I have the following bean defined:
<bean id="myBean" class="com.me.myapp.Widget">
<constructor-arg name="fizz" value="null"/>
<constructor-arg name="buzz" ref="someOtherBean" />
</bean>
When I run my app, Spring throws a bean config exception:
[java] Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myBean' defined in class path resource [spring-config.xml]:
Unsatisfied dependency expressed through constructor argument with index 0
of type [com.me.myapp.Widget]: Could not convert constructor argument value of
type [java.lang.String] to required type [com.me.myapp.Widget]: Failed to
convert value of type 'java.lang.String' to required type
'com.me.myapp.Widget'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required
type [com.me.myapp.Widget]: no matching editors or conversion strategy found
I just want to create a Widget like I would if I wrote the following Java:
Widget w = new Widget(null, someOtherBean);
How can I do this? Thanks in advance!
You can use Spring's <null> tag:
<bean id="myBean" class="com.me.myapp.Widget">
<constructor-arg name="fizz">
<null />
</constructor-arg>
<constructor-arg name="buzz" ref="someOtherBean" />
</bean>
At times spring fails to inject the values in the ordered you have mentioned into a constructor. It's better if you try with explicit ordering, i.e.
<constructor-arg index="0" name="fizz"><null/></constructor-arg>
<constructor-arg index="1" name="buzz"><ref bean="someOtherBean"/></constructor-arg>
this was, actually, not working for me,
so what I've done is, not passing the object through spring,
but asking "if the object is null", and create New object and assign it to it,
it is also done once (similar to spring),
the difference is that, it is not the best practice, and the creation point of the object is in the flow of the class, and not in early stage.

Spring and Hibernate Runtime error

Below error is seen on my eclipse. I am just trying to save a terminalgroup object and was getting an error about TerminalGroupImpl not found. So I created a TerminalGroupImpl.java to be a hibernate file that has the #Entity for the terminal_group table. I have a TerminalGroupDaoHibernate.java file that using the TerminalGroupImpl.class to execute queries on the terminal_group table.
Please if someone can tell me what is wrong with my code and/or what I can do to figure out what is wrong?
Error
Invalid property 'terminalGroupDaoHibernate' of bean class
[com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupServiceImpl]:
Bean property 'terminalGroupDaoHibernate' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
Here is my applicationContext.xml file:
<!-- Terminal Group Service -->
<bean id="com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupService"
class="com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupServiceImpl">
<property name="terminalGroupDao"
ref="com.ccadllc.dac.model.consumer.terminalgroups.dao.TerminalGroupDao"/>
<property name="terminalGroupComponentDao"
ref="com.ccadllc.dac.model.consumer.terminalgroups.dao.TerminalGroupComponentDao"/>
</bean>
<bean id="com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupImpl"
class="com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupImpl" abstract="true">
<property name="terminalGroupDaoHibernate"
ref="com.ccadllc.dac.model.consumer.terminalgroups.dao.TerminalGroupDaoHibernate"/>
</bean>
<bean id="com.ccadllc.dac.model.consumer.terminalgroups.dao.TerminalGroupDao"
class="com.ccadllc.dac.model.consumer.terminalgroups.dao.TerminalGroupDaoHibernate">
<property name="messageService" ref="com.ccadllc.dac.messaging.MessagingService" />
</bean>
under hibernate.annotated.classes:
<value>com.ccadllc.dac.model.consumer.terminalgroups.TerminalGroupImpl</value>
TerminalGroupServiceImpl.java
Getter/Setter in TerminalGroupServiceImpl.java:
private TerminalGroupDao terminalGroupHibernateDao;
/**
* #param TerminalGroupHibernateDao The TerminalGroupHibernateDao to set.
*/
#Required
#Transactional
public void setTerminalGroupHibernateDao(final TerminalGroupDao terminalGroupHibernateDao)
{
this.terminalGroupHibernateDao = terminalGroupHibernateDao;
}
#Required
#Transactional
public TerminalGroupDao getTerminalGroupHibernateDao()
{
return terminalGroupHibernateDao;
}
You are trying to set terminalGroupDaoHibernate property instead of terminalGroupHibernateDao.
The property you have defined in the xml is "terminalGroupDaoHibernate", but the setter in your service impl's name is "setTerminalGroupHibernateDao". There is typo error. The setter name should be "setTerminalGroupDaoHibernate"
You should not add the #Required annotation on a getter. Also, in your bean xml, you use the property name terminalGroupDao but your setter has the name setTerminalGroupHibernateDao rather than setTerminalGroupDao.

Spring Webflow binding: Converter - java.lang.IllegalArgumentException: Each converter object must implement one of the Converter ... interfaces

I have the following code in one of the Spring's XML config files:
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="org.springframework.binding.convert.converters.StringToDate">
<property name="pattern" value="yyyy-MM-dd" />
</bean>
</list>
</property>
</bean>
But I am getting the following exception during deployment (on JBoss):
java.lang.IllegalArgumentException: Each converter object must
implement one of the Converter, ConverterFactory, or GenericConverter
interfaces
Any idea why? As far as I can see, org.springframework.binding.convert.converters.StringToDate is an implementation of Converter.
UPDATE:
Just found this answer, that suggests that mixing Converters and PropertyEditors might cause problems. I do have part in my app that use PropertyEditors, but as far as I can see, the documentation does not talk about any problem with mixing the two systems.
Stack trace:
Caused by: java.lang.IllegalArgumentException: Each converter object must implement one of the Converter, ConverterFactory, or GenericConverter interfaces
at org.springframework.core.convert.support.ConversionServiceFactory.registerConverters(ConversionServiceFactory.java:106)
at org.springframework.context.support.ConversionServiceFactoryBean.afterPropertiesSet(ConversionServiceFactoryBean.java:56)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 146 more
UPDATE 2:
I changed my xml to be:
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="my.project.StringToDate">
<!-- org.springframework.binding.convert.converters.StringToDate DEFAULT_PATTERN = "yyyy-MM-dd" -->
<property name="pattern" value="yyyy-MM-dd" />
</bean>
</set>
</property>
</bean>
My custom converter is:
package my.project;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class StringToDate extends org.springframework.binding.convert.converters.StringToDate implements Converter<String, Date> {
public Date convert(String source) {
Date date = null;
try {
date = (Date) convertSourceToTargetClass(getPattern(), getTargetClass());
} catch (Exception e) {
}
return date;
}
}
HOWEVER, reading the following forum thread I would expect the conversion to work. If I get them right, they are saying that once the converter is set correctly, it should be working with Spring Batch, i.e. it does not require any special setting to make it work specifically with Spring Batch. But I am still getting a BindException during the batch task... any idea why?
See the new stack trace:
Caused by: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'target' on field 'datetimeInactive': rejected value [2011-04-27]; codes [typeMismatch.target.datetimeInactive,typeMismatch.datetimeInactive,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.datetimeInactive,datetimeInactive]; arguments []; default message [datetimeInactive]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'datetimeInactive'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'datetimeInactive': no matching editors or conversion strategy found]
Field error in object 'target' on field 'datetimeActive': rejected value [2011-04-27]; codes [typeMismatch.target.datetimeActive,typeMismatch.datetimeActive,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.datetimeActive,datetimeActive]; arguments []; default message [datetimeActive]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'datetimeActive'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'datetimeActive': no matching editors or conversion strategy found]
at org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper.mapFieldSet(BeanWrapperFieldSetMapper.java:186)
at org.springframework.batch.item.file.mapping.DefaultLineMapper.mapLine(DefaultLineMapper.java:42)
at org.springframework.batch.item.file.FlatFileItemReader.doRead(FlatFileItemReader.java:179)
... 45 more
See also my original question (still unsolved).
Are you sure you should be using the org.springframework.context.support.ConversionServiceFactoryBean? This is a spring-core defined class. It expects the following:
org.springframework.core.convert.converter.GenericConverter
org.springframework.core.convert.converter.Converter
org.springframework.core.convert.converter.ConverterFactory
You are trying to send it a
org.springframework.binding.convert.converters.Converter
One is a spring-core, the other is a spring-webflow converter. You may want to try and create a #Service yourself
#Service("conversionService")
public class MyConversionService extends DefaultConversionService {
public void ConversionService() {
addDefaultConverters();
}
#Override
protected void addDefaultConverters() {
super.addDefaultConverters();
}
}

Categories