org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class - java

I got stuck on this error given below:
Stack Trace
Apr 16, 2014 12:21:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'collectionsWithProps' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class [com.student.spring.impl.CollectionsWithProps]: Bean property 'adminEmails' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at com.student.spring.test.MyTest.main(MyTest.java:26)
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'adminEmails' of bean class [com.student.spring.impl.CollectionsWithProps]: Bean property 'adminEmails' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1064)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:924)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:76)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
... 8 more
Here is my MyTest.java
package com.student.spring.test;
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.student.spring.impl.CollectionsWithProps;
#SuppressWarnings("deprecation")
public class MyTest {
public static void main(String[] args) {
Resource resource = new ClassPathResource("beans.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
CollectionsWithProps cWP = (CollectionsWithProps) beanFactory
.getBean("collectionsWithProps");
System.out.println(cWP);
}
}
Here is CollectionsWithProps.java
package com.student.spring.impl;
import java.util.Properties;
public class CollectionsWithProps {
private Properties emails=null;
public Properties getEmails() {
return emails;
}
public void setEmails(Properties emails) {
this.emails = emails;
}
public String toString(){
return "College [Props=" + emails + "]";
}
}
Here is my beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="collectionsWithProps" class="com.student.spring.impl.CollectionsWithProps">
<property name="adminEmails">
<props>
<prop key="admin">admin#appa.com</prop>
<prop key="support">support#appa.com"></prop>
<prop key="hr">hr#appa.com</prop>
</props>
</property>
</bean>
</beans>

In beans.xml you are trying to set the field adminEmails of CollectionsWithProps.
However the class doesn't have that field, it has the emails field.
Either fix beans.xml to use emails instead of adminEmails, or fix the source code of CollectionsWithProps be renaming emails to adminEmails (along with the getters and setters)

There is property name mismatch:
private Properties emails=null;
should ideally be:
private Properties adminEmails=null;
getters and setters should be renamed accordingly. This will match with what you have mentioned in the configuration files.

I had the same issue and it got resolved by just removing getter. As I required only setter for my application. Sometimes Spring gives this error.

Check for name value in .xml and Variables spelling And case should be same.

Related

Error creating bean with name Unsatisfied dependency expressed through field

It's been 3rd day I've been trying to implement a simple CRUD application using Mybatis XML configuration and I'm new to the whole Spring ecosystem. The question is a bit long but I've only sharec the essentials.
I have a class Employee.java:
import lombok.*;
#Getter #Setter #AllArgsConstructor #NoArgsConstructor #ToString
public class Employee {
private long emp_Id;
private String emp_name;
private String emp_dept;
}
Then I wrote a Mapper
#Mapper
public interface EmployeeMapper {
public Employee getEmployee(#Param("emp_Id") Long emp_Id);
public List<Employee> getAllEmployee();
}
Then I wrote a mapper XML named EmployeeMapper.xml
...
<mapper namespace="Employee">
<select id="getAllEmployee" resultType="com.tmb.mybatiscrudproj.domains.Employee">
select * from employee
</select>
<select id="getEmployee" resultType="com.tmb.mybatiscrudproj.domains.Employee">
select * from employee where emp_Id = #{emp_Id}
</select>
</mapper>
Then I have written a service:
public interface EmployeeService {
public Employee getEmployee(Long emp_Id);
public List<Employee> getAllEmployee();
}
and here is the service implementation:
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
EmployeeMapper employeeMapper;
#Override
public List<Employee> getAllEmployee() {
List<Employee> list = employeeMapper.getAllEmployee();
return list;
}
#Override
public Employee getEmployee(Long emp_Id) {
return employeeMapper.getEmployee(emp_Id);
}
}
and finally the controller class
#RestController
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
EmployeeService empService;
#RequestMapping(value="/getEmp/{empId}",method = RequestMethod.GET)
public Employee getEmployee(#PathVariable Long empId){
return empService.getEmployee(empId);
}
#GetMapping(value="/getAllEmp")
public List<Employee> getAllEmployee(){
return empService.getAllEmployee();
}
I'm confused about the configurations. As I have a built-in application.properties inside the resources older and in it I have:
server.port: 8081
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:~/test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
mybatis.config-location=classpath:mapper/mybatisConfig.xml
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.type-aliases-package=com.tmb.mybatiscrudproj.domains
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=30
Following many tutorials and answers, I created a mybatisConfig.xml and EmployeeMapper.xml file is also inside the `resources folder.
In the mybatisConfig.xml I've done almost the same thing as I did in .properties file
...
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:~/test"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
<property name="path" value="/h2"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>
Here is the screenshot of the project structure:
when I run the project I get the following errors:
Error creating bean with name 'employeeController': Unsatisfied dependency expressed through field 'empService';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeServiceImpl': Unsatisfied dependency expressed through field 'employeeMapper';
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeMapper' defined in file [MY_PATH/mybatiscrudproj/target/classes/com/tmb/mybatiscrudproj/mapper/EmployeeMapper.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [org/mybatis/spring/boot/autoconfigure/MybatisAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is java.lang.IllegalStateException: Property 'configuration' and 'configLocation' can not specified with together
Now based on the searches I have done I made sure the in the main class I add:
#MappedTypes({Employee.class})
#MapperScan("com.tmb.mybatiscrudproj.mapper")
#SpringBootApplication
public class MybatiscrudprojApplication {
public static void main(String[] args) {
SpringApplication.run(MybatiscrudprojApplication.class, args);
}
}
but still the same error. How can I successfully configure the project with the structure I have shared in this question?
Your "employeeMapper" is not declared as a spring bean, so when dependency injection, there's no bean with this type. Try adding a #Component on your class.

Getting NoSuchBeanDefinitionException even after using all annotations and component scan

I am getting
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'springTest': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: com.learn.stackoverflow.general.Person
com.learn.stackoverflow.general.SpringTest.person; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.learn.stackoverflow.general.Person] 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)}
even after using all the annotations, I have annotated all my classes with #Component and adding component scan but still #Autowired gives me error.
Below are my classes:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;
#Component
public class SpringTest {
#Autowired
Person person;
public static void main(String[] args) {
testApplicationContext();
}
private static void testApplicationContext() {
// here static and instance initializers of Person class will be invoked right away, even when we are not calling getBean method
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("C:\\E_Drive\\Projects\\Workspace\\Test\\CS101\\src\\com\\learn\\stackoverflow\\general\\bean.xml");
SpringTest springTest = (SpringTest) applicationContext.getBean("springTest");
}
}
Person class:
import org.springframework.context.annotation.Scope;
import com.bea.core.repackaged.springframework.stereotype.Component;
#Component
#Scope(value="singleton")
public class Person {
static{
System.out.println("1");
}
{
System.out.println("2");
}
}
XML file:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.learn.stackoverflow.general"/>
<!-- <bean id = "person" class = "com.learn.stackoverflow.general.Person" scope="singleton">
</bean> -->
<bean id = "springTest" class = "com.learn.stackoverflow.general.SpringTest" scope="singleton">
</bean>
</beans>
Use the right import in the Person.class. Instead of
import com.bea.core.repackaged.springframework.stereotype.Component;
you have to use
import org.springframework.stereotype.Component;
BTW you can avoid using
#Scope(value="singleton")
since singleton is a default scope for Spring beans.

Error in creation of bean while using #Required and #Autowired

I am new to spring.I am trying to make use #Required and #Autowired in my code but its giving me org.springframework.beans.factory.BeanCreationException.Below is my code.
1) StudentAuto.java
public class StudentAuto
{
#Autowired
private String name;
#Autowired
private String city;
public String getCity() {
return city;
}
#Required
public void setCity(String city) {
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2)spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config></context:annotation-config>
<bean id='stu' class='com.bean.StudentAuto' >
</bean>
<bean name='name' class='java.lang.String'>
<constructor-arg value="nm"></constructor-arg>
</bean>
<bean name='city' class='java.lang.String'>
<constructor-arg value="ci"></constructor-arg>
</bean>
</beans>
3)TestApp.java
public class TestApp {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
StudentAuto auto=context.getBean("stu", StudentAuto.class);
System.out.println(auto.getCity());
System.out.println(auto.getName());
}
}
and error stack trace is below.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stu' defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanInitializationException: Property 'city' is required for bean 'stu'
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
at com.bean.TestApp.main(TestApp.java:14)
Caused by: org.springframework.beans.factory.BeanInitializationException: Property 'city' is required for bean 'stu'
at org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.postProcessPropertyValues(RequiredAnnotationBeanPostProcessor.java:149)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
... 7 more
Please help me on this issue.
The javadoc for #Required states
Marks a method (typically a JavaBean setter method) as being
'required': that is, the setter method must be configured to be
dependency-injected with a value.
Note that the annotated method is not necessarily a setter but that is usually what it is.
#Required methods are processed by RequiredAnnotationBeanPostProcessor which states that
This neatly pushes responsibility for such checking onto the container
(where it arguably belongs), and obviates the need (in part) for a
developer to code a method that simply checks that all required
properties have actually been set.
So the purpose is to guarantee that properties are set by checking if the container has actually invoked the method.
The typical pattern is
class Foo {
private String value;
#Required
public void setValue(String value) {
this.value = value;
}
}
with a bean definition
<bean class="Foo" id="fooBean">
<property name="value" value="some value"/>
</bean>
If you had not added the <property>, the container would complain and throw exceptions, just like it does with your configuration
<bean id='stu' class='com.bean.StudentAuto' >
</bean>
Here, the container is not using the #Required method to set the property. It is using reflection on the Field directly because of #Autowired. Therefore the #Required annotation is not validated.
1. DOC:
#Required
This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring.
2. Please pay attention:
#Required annotation is used for validation checking, not for dependency injection.
3. A way to fix:
As the error log shows: Property 'city' is required for bean 'stu'. So, you should add a propery tag into the stu bean - inject city manually:
<bean id="stu" class="com.bean.StudentAuto">
<property name="city" value="London"/>
</bean>

Error creating bean with name 'countriesDao': Injection of autowired dependencies failed;

Im trying to start Tomcat but when I try start it im getting the following error
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'countriesDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.fexco.helloworld.web.util.CustomHibernateDaoSupport.anyMethodName(org.hibernate.SessionFactory); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
CountriesDao
package com.fexco.helloworld.web.dao;
import com.fexco.helloworld.web.model.Countries;
public interface CountriesDao {
void save(Countries countries);
void update(Countries countries);
void delete(Countries countries);
Countries findByCountry(String country);
}
The start of CountriesDaoImpl
package com.fexco.helloworld.web.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.fexco.helloworld.web.model.Countries;
import com.fexco.helloworld.web.util.CustomHibernateDaoSupport;
#Repository("countriesDao")
public class CountriesDaoImpl extends CustomHibernateDaoSupport implements CountriesDao{
public void save(Countries countries){
getHibernateTemplate().save(countries);
}
......
}
Some of Application-config.xml
<bean id="countriesDao" class="com.fexco.helloworld.web.dao.CountriesDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
....
<context:annotation-config />
<context:component-scan base-package="com.fexco.helloworld.web" />
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
CustomHibernateDaoSupport class
package com.fexco.helloworld.web.util;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public abstract class CustomHibernateDaoSupport extends HibernateDaoSupport
{
#Autowired
public void anyMethodName(SessionFactory sessionFactory)
{
setSessionFactory(sessionFactory);
}
}
Is the error because CountriesDaoImpl isnt really implementing CountriesDao?
Does anyone know how to solve this error?
Thanks
It seems you do not have session factory defined in your dao Implementation class. You should defined one if not already defined And avoid using both configurations It will messed up things i.e
#Autowired
#Qualifier("sessionFactory")
public void seSessionFactory(SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}

IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required when extending JdbcUserDetailsManager

I´m pretty new to Spring, and I´m currently struggling with an exception being thrown when I´m attempting to extend JdbcUserDetailsManager since I need additional features besides the ones provided. The class signature looks looks like this, with a default constructor.
#Repository
public class PrimeUserDetailsManager extends JdbcUserDetailsManager implements CustomUserDetailsManager {
public static String CUSTOM_USERS_BY_USERNAME_QUERY = "select username,password,enabled from users where username like ?%";
public static String FIND_ALL_USERS_QUERY = "select username,password,enabled from users";
#Override
public List<UserDetails> loadUsersByUsername(String username) {
return super.loadUsersByUsername(username);
}
#Override
public List<UserDetails> findAllUsers() {
return getJdbcTemplate().query(FIND_ALL_USERS_QUERY, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
boolean enabled = rs.getBoolean(3);
return new User(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
}
});
}
}
}
My custom Interfaces looks like this:
public interface CustomUserDetailsManager extends UserDetailsManager {
public List<UserDetails> loadUsersByUsername(String username);
public List<UserDetails> findAllUsers();
}
Simple autowire:
#Service("userService")
public class UserServiceImpl implements UserService{
#Autowired
public UserServiceImpl(CustomUserDetailsManager customUserDetailsManager) {
this.customUserDetailsManager = customUserDetailsManager;
}
private CustomUserDetailsManager customUserDetailsManager;
....
}
And in my ApplicationContext, I have this:
<beans:bean id="jdbcUserService" class="org.primefaces.examples.moviecollector.custom.PrimeUserDetailsManager">
<beans:property name="dataSource" ref="dataSource"/>
<beans:property name="authenticationManager" ref="authenticationManager"/>
<beans:property name="enableGroups" value="true"/>
<beans:property name="enableAuthorities" value="false"/>
</beans:bean>
Still, when staring my application, I get the exception below, so apperently I must have missed something? Can someone please tell me what?
Complete stacktrack:
2011-sep-07 13:08:49 org.apache.catalina.core.StandardContext listenerStart
ALLVARLIG: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userBean' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\beans\UserBean.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.security.provisioning.GroupManager]: : Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:730)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4701)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5204)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5199)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'primeUserDetailsManager' defined in file [C:\Program\springsource\vfabric-tc-server-developer-2.5.0.RELEASE\Localhost\wtpwebapps\prime-sweet\WEB-INF\classes\org\primefaces\examples\moviecollector\custom\PrimeUserDetailsManager.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:786)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723)
... 23 more
Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
at org.springframework.jdbc.core.support.JdbcDaoSupport.checkDaoConfig(JdbcDaoSupport.java:112)
at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 34 more
EDIT:
I´ve included the entire body of PrimeUserDetailsManager above. Here´s the dataSource definition:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
You've got two beans. One is defined in XML. There's another one being created because you've annotated your class with #Repository. That's the one giving you the trouble because you haven't given it any instructions about wiring the required "'dataSource' or 'jdbcTemplate'". Note in the exception that the bean's name is given as "primeUserDetailsManager". That's the lower-cased simple class name, which is the default name for beans created via component scanning with annotations.
I create an intermediate JdbcDaoSupport derived super class that all my DAO classes extend from that looks like this:
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class MyJdbcDaoSupport extends JdbcDaoSupport {
#Autowired private DataSource dataSource;
#PostConstruct
private void initialize() {
setDataSource(dataSource);
}
}
This assumes you have a data source bean with id "dataSource", as shown by the OP.
Works for me in Spring 4.x but should work with earlier versions too.
The only way I managed to solve is by defining following in my DAO.
private SimpleJdbcTemplate simpleJdbcTemplate;
protected SimpleJdbcTemplate getSimpleJdbcTemplate() {
return simpleJdbcTemplate;
}
#Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
It seems the SimpleJdbcDaoSupport does not have #Autowired annotation to its setDataSource method.
This works even in spring 2.5
/**
* Sets the parent class DataSource to the auto-wired data source.
*
*
*/
#Autowired
public void setParentDataSource(
#Qualifier("dataSource") DataSource dataSource) {
super.setDataSource(dataSource);
}

Categories