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

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>

Related

Bean instance is not getting loaded

I need a help regarding dependency injection.
I hava a bean class which is having a object reference of JdbcTemplate and I am using #Autowired to
create instance of that object. But that object is not getting loaded and as a result NullPointerException is thrown
from setCustName() method.
Please help
Bean Class :
class CustomerBean {
private String custName;
#Autowired
private JdbcTemplate jdbcTemplate;
public void setCustName(String custName) {
this.custName = custName;
jdbcTemplate.update(query);
}
}
XML :
<bean id="myjdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="custBean" class="com.test.CustomerBean">
<property name="custName" value="John" />
</bean>
Stacktrace:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'custName' threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:334)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1419)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
you get NullPointerException as jdbcTemplate is null / not injected.
if you describe bean custBean by xml , as you did, you should add :
< property name="jdbcTemplate" value="myjdbcTemplate" /> for inject jdbcTemplate into your bean.
you have mixed configuration - xml and annotation. in your xml should be :
<context:component-scan base-package="package....." />
to support #Autowired and CustomerBean should be #service or #component.
vaiant1 :
add into xml and
#Component
class CustomerBean {
private String custName;
#Autowired
private JdbcTemplate jdbcTemplate;
public void setCustName(String custName) {
this.custName = custName;
jdbcTemplate.update(query);
}
}
variant2 :
class CustomerBean {
private String custName;
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
this.jdbcTemplate = jdbcTemplate;
}
public void setCustName(String custName) {
this.custName = custName;
jdbcTemplate.update(query);
}
}
and xml
<bean id="custBean" class="com.test.CustomerBean">
<property name="custName" value="John" />
<property name="jdbcTemplate" ref="myjdbcTemplate" />
</bean>
Add #Component annotation to the bean class which contains beans that can be autowired.
After adding the above #Component annotation on beans, we need to tell spring to scan these respective beans and load all the autowired dependencies. This can be done by declaring the following XMLconfiguration
<context:component-scan base-packages="<your_package_names>"/>
for example if my package structure is com.mycompany
<context:component-scan base-packages="com.mycompany"/>
Use <context:annotation-config> which enables the usage of different annotations in bean classes.
Also I strongly recommend against usage of different dependencies in properties setters. In your code sample you assume that the jdbcTemplate was autowired before the call of the setter, fact that you cannot be sure of.
Therefore the logic that you placed in the setter, regarding the jdbc template would be more properly placed in a method annotated with #PostConstruct.

Autowiring against Interface returns null - Spring MVC

I am working on this Spring MVC project where I have trouble getting this Dao class auto wired in the controller through an Interface that is implemented by the Dao. This is portion of my spring-config.xml. I am using aspectJ, Annotation and TX management.
<aop:aspectj-autoproxy />
<context:component-scan base-package="com.simulator" />
<context:annotation-config />
<tx:annotation-driven />
<context:property-placeholder
location="classpath*:config.properties" />
<bean id="oidDao" class="com.simulator.service.OidDao">
<property name="ipaddressNC" value="${ipaddressNC}" />
<property name="ipaddressOM" value="${ipaddressOM}" />
</bean>
Dao class:
#Component
public class OidDao implements OidManager {
#Autowired
private SessionFactory sessionFactory;
private String ipaddressNC;
private String ipaddressOM;
public String getIpaddressNC() {
return this.ipaddressNC;
}
public void setIpaddressNC(String ipaddressNC) {
this.ipaddressNC = ipaddressNC;
}
public String getIpaddressOM() {
return ipaddressOM;
}
public void setIpaddressOM(String ipaddressOM) {
this.ipaddressOM = ipaddressOM;
}
OidManager:
public interface OidManager {
public String getIpaddressNC();
public String getIpaddressOM();
}
Controller:
#Controller
public class HomeController {
#Autowired
OidManager oim;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String indexpage(ModelMap modelMap) {
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"spring-config.xml"});
o = (OidManager)context.getBean("oidDao");
o.getIpaddressNC(); // ---> this returns data read from ext properties file and works fine
oim.getIpaddressNC(); // ---> this returns null`
I am trying to re-use the Dao, hence I dont want to call the ApplicationContext multiple times from each method. What am I doing wrong? If I make the variables getIpaddressNC, getIpaddressOM static, then auto wiring works, if not oim returns null though the variables are initialized via setters on application load.
You used both Component Scanning and Manual Wiring for OidDao. You defined oidDao in xml config, as follows:
<bean id="oidDao" class="com.simulator.service.OidDao">
<property name="ipaddressNC" value="${ipaddressNC}" />
<property name="ipaddressOM" value="${ipaddressOM}" />
</bean>
Then, added a Component annotation on OidDao, as follows:
#Component
public class OidDao implements OidManager {
...
}
Drop the Component annotation and you'll be fine, i guess! Because otherwise, <context:component-scan base-package="com.simulator" /> will pick OidDao and instantiate an instance from it with default constructor and without calling your setters.
You are using #Component annotation + you have also defined a bean. Therefore actually two beans are created. One created due to use of #Component would have the properties set to 'null'. This is expected since you are not setting the properties to any value. Either remove #Component annotation and use 'autowire-candidate="true"' property on bean definition or else remove the bean definition in XML and use relevant annotation on the class to set properties to correct values from property file.
Change your bean definition to:
<bean id="oim" class="com.simulator.service.OidDao">
<property name="ipaddressNC" value="${ipaddressNC}" />
<property name="ipaddressOM" value="${ipaddressOM}" />
</bean>
Let this create bean with id oim which can be set to the property oim in your Controller.

Spring BeanPostProcessor not get called its implemented bean , but invoke for all other beans

my bean.xml
hi friends.., i am just learning spring . i implement the interface BeanPostProcessor in HelloWorld.java . its methods invoked for all other beans , but not itself(Helloworld.java bean)
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld" > </bean>
<!-- Definition for textEditor bean -->
<bean id="textEditor" class="com.tutorialspoint.TextEditor">
<property name="spellChecker" ref="spellChecker"/>
</bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
</bean>
Helloworld.java
public class HelloWorld implements BeanPostProcessor {
#Override
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
System.out.println();
System.out.println(bean.getClass().getName() +"---------------"+name+"--->This is after bean initialized ");
return bean;
}
#Override
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
System.out.println(bean.getClass().getName() +"---------------"+name+"----------->This is before bean initialized ");
return bean;
}
}
main program
public class MainApp {
public static void main(String arg[])throws Exception{
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Bean.xml");
}
}
my output is
com.tutorialspoint.SpellChecker---------------spellChecker----------->This is before bean initialized
com.tutorialspoint.SpellChecker---------------spellChecker--->This is after bean initialized
com.tutorialspoint.TextEditor---------------textEditor----------->This is before bean initialized
com.tutorialspoint.TextEditor---------------textEditor--->This is after bean initialized
why BeanPostProcessor interface methods not invoked for HelloWorld.java ..,but invoked for other unrelated beans which is not implementing BeanPostProcessor interface ..?
any bean implementing BeanPostprocessor works as bean postprocessor for all beans.Please refer URL for more details.It is clearly mentioned that ApplicationContexts can autodetect BeanPostProcessor beans in their bean definitions and apply them to any beans subsequently created. **Plain bean factories allow for programmatic registration of post-processors, applying to all beans created through this factory**.
Do you want a specific bean having some initializing code then implement InitializingBean as below
package org.studyspring.beanfactory
public class HelloWorld implements InitializingBean {
private String name;
public void setName(String name) {
this.name = name;
}
#Override
public void afterPropertiesSet() throws Exception {
System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is after bean initialized ");
}
}
add entry for this bean in XML
<bean id="helloWorld" class="org.studyspring.beanfactory.HelloWorld">
<property name="name" value="Shirish"/>
</bean>
or alternatively you can have init and destroy methods for each bean as below
package org.studyspring.beanfactory;
import org.springframework.beans.factory.InitializingBean;
public class HelloWorld1 {
private String name;
public void setName(String name) {
this.name = name;
}
public void init() throws Exception {
System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is before bean initialized");
}
public void destroy() throws Exception {
System.out.println(this.getClass().getName() +"---------------name = "+name+"--->This is after bean destroyed ");
}
}
register your bean as below in XML
<bean id="helloWorld1" class="org.studyspring.beanfactory.HelloWorld1" init-method="init" destroy-method="destroy">
<property name="name" value="Shirish"/>
</bean>
Additionally if you follow common practice for naming init & destroy methods then you can define those methods in <beans> as below
<beans default-init-method="init" default-destroy-method="destroy">
with above the beans which have init and destory methods available they will be called upon initialization and destructions of those beans

#Autowired fields causes org.springframework.beans.factory.BeanCreationException

When i try to use #Autowired it gives me exceptions
Things I have added to use #Autowired annotation
context:annotation-config /
bean id = "GoAnalyserService" class ="com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/
context:component-scan base-package="com.dataanalyser.service"/
My spring-dispatcher-servlet
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:component-scan base-package="com.dataanalyser.controller"/>
<!-- <context:component-scan base-package="com.dataanalyser"/> -->
<context:component-scan base-package="com.dataanalyser.dao"/>
<context:component-scan base-package="com.dataanalyser.service"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:annotation-config />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/" />
<property name = "suffix" value = ".html" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/GoAnalyserDB" />
<property name="username" value="postgres" />
<property name="password" value="toor" />
</bean>
<bean id = "goAnalyserService" class = "com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/>
<bean id = "userDao" class = "com.dataanalyser.daoimpl.UserDaoImpl"/>
</beans>
My controller class
#Controller
public class GoAnalyserControl {
public GoAnalyserControl()
{
System.out.println("------- Inside the controller -------");
}
#Autowired
GoAnalyserService goAnalyserService;
#RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"})
public #ResponseBody String logInCheckerFn(#RequestBody UserLogData userLogData){
System.out.println("inside loginChecker()");
//GoAnalyserService goAnalyserService = new GoAnalyserServiceImpl();
Integer userAuthFlag = goAnalyserService.checkUserAuth(userLogData);
System.out.println(userAuthFlag.toString());
return userAuthFlag.toString();
}
}
My Service class
public interface GoAnalyserService {
public Integer checkUserAuth(UserLogData userLogData);
}
My Service implementation class
public class GoAnalyserServiceImpl implements GoAnalyserService {
#Autowired
UserDao userDao;
#Override
public Integer checkUserAuth(UserLogData userLogData){
//UserDao userDao = new UserDaoImpl();
if((userDao.getUserCount(userLogData.getUserName())) == 1){
String dbPass = userDao.getUserPass(userLogData.getUserName());
if( dbPass.equals(userLogData.getPassword()))
return 1;
else
return 2;
}else
return 0;
}
}
When i try it out without #Autowired annotation, this code works out fine, but when i add #Autowired it gives me
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'goAnalyserControl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.dataanalyser.service.GoAnalyserService com.dataanalyser.controller.GoAnalyserControl.goAnalyserService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.dataanalyser.service.GoAnalyserService com.dataanalyser.controller.GoAnalyserControl.goAnalyserService; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.dataanalyser.serviceimpl.GoAnalyserService] for bean with name 'GoAnalyserService' defined in ServletContext resource [/WEB-INF/spring-dispatcher-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.dataanalyser.serviceimpl.GoAnalyserService
and few more like this,
I think something is wrong in spring-dispatcher-servlet.xml, I have searched a lot, still cant find the thing wrong. I there any jar file that need to be added to the project ....??
Put #Repo on GoAnalyserServiceImpl class
May be resolve your error beacuse when you used #Autowired you dont wory about creating object.And use #Autowired must be at top of class #Controller or #Repo or #Service / only #Component. annotation is used to mark the class as the controller in Spring 3.
Try to remove
<bean id = "goAnalyserService" class = "com.dataanalyser.serviceimpl.GoAnalyserServiceImpl"/>
from xml configuration.
And annotate GoAnalyserServiceImpl as #Component.
First of all, make sure that the class you are declaring in your XML exists inside the package. Then, annotate your class with #Component annotation. Spring uses these annotations to find the class it is supposed to instantiate when #Autowired is used.
Your component-scan declaration is:
<context:component-scan base-package="com.dataanalyser.service"/>
while your exception message states that :
Cannot find class com.dataanalyser.serviceimpl.GoAnalyserService
So you have a wrong package declaration in your component scan. Make it :
<context:component-scan base-package="com.dataanalyser.serviceimpl"/>
or change the package of the class to com.dataanalyser.service
Assuming of course that your service class is annotated properly

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

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.

Categories