UnsatisfiedDependencyException during Spring Injection - spring

I am getting this error for using Spring injection using constructor argument:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'testIdCreator': Unsatisfied dependency
expressed through constructor argument with index 0 of type
[IdCreatorDao]: : No matching bean of type [com.dao.IdCreatorDao
Bean definition:
<bean id="testIdCreator" class="com.utils.TestIdCreator">
<constructor-arg ref="mydDao"/>
</bean>
<bean id="mydDao" class="com.dao.idCreatorDAOImpl">
<constructor-arg ref="somedatasource" />
<constructor-arg value="${somedatasource.schema}" />
</bean>
Bean usage:
public class TestIdCreator{
private final IdCreatorDao idDao;
#Inject
public TestIdCreator(IdCreatorDao idDao) {
this.idDao= idDao;
}
}

Related

Unable to locate a ejb in spring context

I am trying to use a EJB singleton bean inside of spring bean but somehow it unable to locate a this ejb and getting a message when run a server:
SEVERE: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationFailureHandler' defined in class path resource [spring-security-config.xml]: Cannot resolve reference to bean 'loginAttemptService' while setting bean property 'loginAttemptService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'loginAttemptService' is defined
Here is a EJB:
public interface ILoginAttemptService {
public boolean checkout(String username);
}
Here is implementation:
#Slf4j
#Stateless(name = "loginAttemptService")
#Singleton
public class LoginAttemptsService implements ILoginAttemptService {
..
}
In spring framework this is how i define a stateless bean:
<bean id="loginAttemptServiceBean"
class="org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean">
<property name="jndiName"
value="java:app/osloproject-ejb/loginAttemptService"/>
<property name="businessInterface"
value="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
</bean>
<bean id="authSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="redirectStrategy">
<bean class="com.hospitality.hp.securitycommons.tools.spring.CORSCompatibleTwoFactorAuthenticationRedirectStrategy">
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
</property>
</bean>
<bean id="authenticationFailureHandler"
class="com.hospitality.hp.securitycommons.tools.spring.AuthenticationFailureCustomHandler">
<property name="useForward" value="true"/>
<property name="defaultFailureUrl" value="/login.jsp"/>
<property name="loginAttemptService" ref="loginAttemptServiceBean"/>
</bean>
Can someone tell me why it unable to find the JNDI name of this EJB ?
try
<jee:local-slsb id="loginAttemptServiceBean" jndi-name="java:app/osloproject-ejb/loginAttemptService"
business-interface="com.hospitality.hp.securitycommons.api.ILoginAttemptService"/>
"jee" is Spring’s namespace.and also check the jndi-name value is correct

Spring use Autowired annotations gets wrong

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="filterChainDefinitionMap" ref="chainFilterBuff" />
</bean>
<bean id="chainFilterBuff" class="org.moofie.test.security.FilterChainBean">
<property name="filterChainDefinitions">
<value>/test/login=anon</value>
</property>
</bean>
above is my spring config
private String filterChainDefinitions;
public String getFilterChainDefinitions() {
return filterChainDefinitions;
}
public void setFilterChainDefinitions(String filterChainDefinitions) {
this.filterChainDefinitions = filterChainDefinitions;
}
and this is my java code,it works fine with getter and setter,but I want to replace getter and setter with #autowired annotaion like this:
#Autowired
private String filterChainDefinitions;
it gets errors:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 34 more
So whats wrong with my code?or I should use other annotations?
The setter and getter way is working because, in your config XML you are calling the setter directly using the <property name="filterChainDefinitions"></property>.
#Autowired works on the bean that are declared explicitly.
If you want to use the #Autowired to set the filterChainDefinitions, then you must declare the it first like below:
<bean id="filterChainDefinitions" class="java.lang.String">
<constructor-arg value="/test/login=anon"/>
</bean>

org.springframework.beans.factory.BeanCreationException: Could not autowire field:

I have problems with:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'itemsController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hdx.ssm.service.ItemsService com.hdx.ssm.controller.ItemsController.itemsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.hdx.ssm.service.ItemsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is ItemsController:
#Controller
#RequestMapping("/items")
public class ItemsController {
#Autowired
private ItemsService itemsService;
and ItemsService:
public interface ItemsService {
Implementation class:
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
And some setting spring-mvc.xml:
<context:component-scan base-package="com.hdx.ssm.controller"/>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
How can i solve this problem?
You need to add #Service as shown below to your ItemsServiceImpl in order to Spring container to know that it is a Spring managed bean:
#Service
public class ItemsServiceImpl implements ItemsService {
#Autowired
private ItemsMapperCustom itemsMapperCustom;
#Autowired
private ItemsMapper itemsMapper;
//other code
}

create a bean from jobparameter in spring batch

I want to a create bean with some of job parameters. I found one thread here
but that seems to unsolved and was an old post.
<bean id="context" class="com.test.MyConfig" scope="step" >
<property name="toDate" value="#{jobParameters['toDate']}" />
<property name="fromDate" value="#{jobParameters['fromDate']}" />
</bean>
<bean id="testId" class="com.test.SomeClass" scope="step" >
<property name="context" ref="context" />
</bean>
And setter attribute is like below And MyConfig does not implement any interface.
MyConfig config;
public void setConfig(MyConfig config)
{
this.config = config
}
I get an exception
Error creating bean with name 'lazybidingProxy.anotherBean' defined in
class path [resource/config/spring-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportException: Failed to convert value of type 'com.sun.proxy.$Proxy17 implementing org.springframework.beans.factory.Initializing,java.io.Serializable,org.springframework.aop.scope.ScopedObject.....
to required type[package.someClass]: no matching editors or conversion strategy found]

creating custom ItemReader with defaultLineMapper using spring annotations

I am trying to make a annotation based ItemReader in spring-batch. I was able to make the desired ItemReader in my xml but annotation based is not at all working giving the following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'runScheduler': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.Job com.techavalanche.batch.RunScheduler.job; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reportJob': Cannot create inner bean '(inner bean)#3f9bb1' of type [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean] while setting bean property 'flow'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3f9bb1': Cannot create inner bean '(inner bean)#17e6f05' of type [org.springframework.batch.core.job.flow.support.StateTransition] while setting bean property 'stateTransitions' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#17e6f05': Cannot create inner bean '(inner bean)#66da50' of type [org.springframework.batch.core.job.flow.support.state.StepState] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66da50': Cannot resolve reference to bean 'step1' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'customItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customItemReader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.springframework.batch.item.file.FlatFileItemReader com.techavalanche.reader.CustomReader.itemReader; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getFlatFileItemReader' defined in class path resource [com/techavalanche/reader/CustomReader.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: LineMapper is required
and it is caused by :
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.batch.core.Job com.techavalanche.batch.RunScheduler.job; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'reportJob': Cannot create inner bean '(inner bean)#3f9bb1' of type [org.springframework.batch.core.configuration.xml.SimpleFlowFactoryBean] while setting bean property 'flow'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#3f9bb1': Cannot create inner bean '(inner bean)#17e6f05' of type [org.springframework.batch.core.job.flow.support.StateTransition] while setting bean property 'stateTransitions' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#17e6f05': Cannot create inner bean '(inner bean)#66da50' of type [org.springframework.batch.core.job.flow.support.state.StepState] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#66da50': Cannot resolve reference to bean 'step1' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'step1': Cannot resolve reference to bean 'customItemReader' while setting bean property 'itemReader'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customItemReader': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public org.springframework.batch.item.file.FlatFileItemReader com.techavalanche.reader.CustomReader.itemReader; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getFlatFileItemReader' defined in class path resource [com/techavalanche/reader/CustomReader.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: LineMapper is required
My CustomReader is
package com.techavalanche.reader;
#Component("customReader")
public class CustomReader implements ItemReader<Report> {
#Autowired
public FlatFileItemReader<Report> itemReader;
#Bean
public FlatFileItemReader getFlatFileItemReader(){
return new FlatFileItemReader();
}
#Bean
public DefaultLineMapper getDefaultLineMapper(){
return new DefaultLineMapper();
}
#Autowired
public DefaultLineMapper<Report> lineMapper;
#Bean
public FixedLengthTokenizer getLinetokenizer(){
return new FixedLengthTokenizer();
}
#Autowired
public FixedLengthTokenizer linetokenizer;
#Bean
public BeanWrapperFieldSetMapper getBeanWrapperFieldSetMapper() {
return new BeanWrapperFieldSetMapper();
}
#Autowired
public BeanWrapperFieldSetMapper<Report> fieldSetMapper;
public Resource res=new FileSystemResource("D:\\testresource\\report.csv");
String[] names= {"date","impressions","clicks","earning"};
#Override
public Report read() throws Exception, UnexpectedInputException, ParseException,
NonTransientResourceException {
for(String name:names){
System.out.println(name);
}
linetokenizer.setNames(new String[] {"date","impressions","clicks","earning"});
Range range1=new Range(1,12);
Range range2=new Range(13,15);
Range range3=new Range(16,20);
Range range4=new Range(21,28);
Range[] ranges={range1,range2,range3,range4};
linetokenizer.setColumns(ranges);
lineMapper.setLineTokenizer(linetokenizer);
fieldSetMapper.setPrototypeBeanName("report");
lineMapper.setFieldSetMapper(fieldSetMapper);
itemReader.setResource(res);
itemReader.setLineMapper(lineMapper);
itemReader.open(new ExecutionContext());
Report report= itemReader.read();
return report;
}
}
My Xml Configuration looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:batch="http://www.springframework.org/schema/batch"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/batch
http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
">
<context:component-scan base-package="com.techavalanche" />
<bean id="jobRepository"
class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />
<bean id="jobLauncher"
class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<bean id="report" class="com.techavalanche.batch.Report" scope="prototype" />
<bean id="customWriter" class="com.techavalanche.writer.CustomWriter" />
<batch:job id="reportJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="customItemReader" writer="customWriter"
commit-interval="2">
</batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
<bean id="multiResourceReader"
class=" org.springframework.batch.item.file.MultiResourceItemReader">
<property name="resources" value="file:D:\testresource\report.csv" />
<property name="delegate" ref="cvsFileItemReader" />
</bean>
<bean id="customItemReader" class="com.techavalanche.reader.CustomReader" />
<bean id="cvsFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
<!-- Read a csv file -->
<!-- <property name="resource" ref="resource" /> -->
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<!-- split it -->
<property name="lineTokenizer">
<bean id="fixedLengthLineTokenizer"
class="org.springframework.batch.item.file.transform.FixedLengthTokenizer">
<property name="names" value="date,impressions,clicks,earning" />
<property name="columns" value="1-12,13-15,16-20,21-28" />
</bean>
</property>
<property name="fieldSetMapper">
<!-- return back to reader, rather than a mapped object. -->
<!-- <bean class="org.springframework.batch.item.file.mapping.PassThroughFieldSetMapper"
/> -->
<!-- map to an object -->
<bean
class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="report" />
</bean>
</property>
</bean>
</property>
</bean>
</beans>

Resources