Not able to autowire a bean using constructor in Spring - java

Im new to spring. I'm trying to autowire a bean using constructor using spring. Here is the code
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
</bean>
<bean id="address" class="com.ibm.spring.Address">
<property name="id" value="2"></property>
<property name="street" value="shahjahan"></property>
</bean>
location class
public class Location {
private Address address;
private String pincode;
public void setAddress(Address address) {
this.address = address;
}
#Autowired
public Location(Address address, String pincode) {
super();
this.address = address;
this.pincode = pincode;
}
public void getTotalAddress() {
System.out.println(this.pincode + "::"+this.address);
}
}
Address class
public class Address {
private int id;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = "Kkp";
}
#Override
public String toString() {
return "Address [id=" + id + ", street=" + street + "]";
}
Tester
public class SpringTester {
public static void main(String[] args) {
String configLoc = "com/ibm/spring/config/applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLoc);
Location l = (Location) ctx.getBean("location");
l.getTotalAddress();
}
}
I'm setting one of the field value through constructor arg. and class should be injected. WHat could be the problem here?
The error log says
Error creating bean with name 'location' defined in class path resource [com/ibm/spring/config/applicationContext.xml]: Unsatisfied dependency expressed through constructor parameter 0: Ambiguous argument values for parameter of type [com.ibm.spring.Address] - did you specify the correct bean references as arguments?

It seems like Location has two arguments so:
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
<constructor-arg ref="address"></constructor-arg>
</bean>

Related

Autowired annotation error in spring with java

I have created a package com.springcore.autowire.Annotations which contains 4 files Emp.java, Address.java, awannconfig.xml, Test.java .
Emp.java contains class Emp with code as -
package com.springcore.autowire.Annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Emp {
private Address address;
public Address getAddress() {
return this.address;
}
#Autowired
#Qualifier("address")
public void setAddress(Address address) {
this.address = address;
}
public Emp(Address address) {
this.address = address;
}
#Override
public String toString() {
return "{" + " address='" + getAddress() + "'" + "}";
}
}
Address.java contains class Address with code-
package com.springcore.autowire.Annotations;
public class Address {
private String street;
private String city;
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
#Override
public String toString() {
return "{" + " street='" + getStreet() + "'" + ", city='" + getCity() + "'" + "}";
}
}
awannconfig.xml file -
<?xml version="1.0" encoding="UTF-8"?>
<!-- We get this template from documentation -->
<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:annotation-config />
<bean class="com.springcore.autowire.Annotations.Emp" name="emp" />
<bean class="com.springcore.autowire.Annotations.Address" name="address">
<property name="street" value="PA-24" />
<property name="city" value="Muradnagar" />
</bean>
<!-- more bean definitions go here -->
</beans>
Test.java contains Test class with main method to check use of #Autowired annotations .
package com.springcore.autowire.Annotations;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/springcore/autowire/Annotations/awannconfig.xml");
Emp obj = (Emp) context.getBean("emp");
System.out.println(obj);
}
}
When I run Test.java file it is showing this exception -
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emp' defined in class path resource [com/springcore/autowire/Annotations/awannconfig.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'address' defined in class path resource [com/springcore/autowire/Annotations/awannconfig.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
Please help with this code as I cannot see any error.
The issue is coming due to parameterised constructor in the Address class whose constructor expects two parameters to be used to create a bean or object when you autowire it as there is no default constructor available.
Solution of the issue.
Keep Emp class as it is :
public class Emp {
private Address address;
public Address getAddress() {
return this.address;
}
#Autowired
#Qualifier("address")
public void setAddress(Address address) {
this.address = address;
}
public Emp(Address address) {
this.address = address;
}
#Override
public String toString() {
return "{" + " address='" + getAddress() + "'" + "}";
}
}
Keep Address class it is :
public class Address {
private String street;
private String city;
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
#Override
public String toString() {
return "{" + " street='" + getStreet() + "'" + ", city='" + getCity() + "'" + "}";
}
}
Update awannconfig.xml to this :
<?xml version="1.0" encoding="UTF-8"?>
<!-- We get this template from documentation -->
<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:annotation-config />
<bean class="com.springcore.autowire.Annotations.Emp" name="emp" />
<bean class="com.springcore.autowire.Annotations.Address" name="address">
<constructor-arg value="PA-24" type="String"/>
<constructor-arg value="Muradnagar" type="String"/>
</bean>
<!-- more bean definitions go here -->
</beans>
Output on my console.
{ address='{ street='PA-24', city='Muradnagar'}'}
Remember : Don't mix both constructor or setter injection as this will lead to confusion and unwanted errors.
Change bean configuration with constructor arg dependency injection, you missed that in emp bean definition. Change bean definition like below.
<bean class="com.springcore.autowire.Annotations.Emp" id="emp">
<constructor-arg ref = "address"/>
</bean>
<bean class="com.springcore.autowire.Annotations.Address" id="address">
<property name="street" value="PA-24" />
<property name="city" value="Muradnagar" />
</bean>

Could not resolve matching constructor.Ambiguity issue with Spring dependency injection

I am getting the error "Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)" while executing my spring program. I am new to Spring core and trying to learn the framework. Below is the code:
Student.java
package com.inject.test;
public class Student {
private String name;
private String className;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Address.java
package com.inject.test;
public class Address {
private String city;
private String state;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Test.java
package com.inject.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("file:com/applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println("Name: " + student.getName());
System.out.println("Class: " + student.getClassName());
Address studentAddress = student.getAddress();
System.out.println("Student Address: ");
System.out.println("City: " + studentAddress.getCity());
System.out.println("State: " + studentAddress.getState());
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="student" class="com.inject.test.Student">
<property name="name" value="Jai"/>
<property name="className" value="MCA"/>
<constructor-arg ref="address" type="java.lang.String"/>
</bean>
<bean id="address" class="com.inject.test.Address">
<property name="city" value="Hyderabad"/>
<property name="state" value="Telangana"/>
</bean>
</beans>
What change should be made to resolve the constructor issue, please suggest.
Your xml configuration specifies a constructor argument containing the address, but your Student class does not have a constructor that takes any arguments.
Either add the appropriate constructor, or change the constructor-arg to a property in the xml configuration.
1)you have not added constructor in your class,so replace your applicationContext.xml file
<bean id="student" class="com.inject.test.Student">
<property name="name" value="jai"></property>
<property name="className" value="MCA"></property>
//instead of writing <constructor-arg>property write as follow
<property name="address" ref="addressOne"></property>
</bean>
<bean id="addressOne" class="com.inject.test.Address">
<property name="city" value="Hyderabad"/>
<property name="state" value="Telangana"/>
</bean>
or 2) just add
public Student(Address address) {
this.address = address;
}
in student class
and replace this line
<constructor-arg ref="address" type="java.lang.String"/>
with this
<constructor-arg ref="address"/>

Spring #Qualifier value at runtime

Is it possible to assign #Qualifier value at runtime. Let's say I have two beans of same type and a class with dependency injection
<bean id="typeA" class="com.debopam.test.Type">
<property name="typevalue" value="Export" />
</bean>
<bean id="typeB" class="com.debopam.test.Type">
<property name="typevalue" value="Import" />
</bean>
public class Product {
private Integer price;
private String name;
#Autowired
#Qualifier("typeB")
private Type type;
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Type getType() {
return type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Is there any way to define type in Product class in runtime instead of hard coding/specifying the value? If yes could you please post some code, otherwise is it advisable to use ApplicationContext.getBean("bean name") to load the bean at runtime?
Yes, I see that you defined two beans for a class. The #Qualifier annotation will tell the class which bean has to be used from the spring configuration file

Java - Hibernate Exception - Feedback cannot be mapped [ from Feedback ]

I am new to Hibernate. Recently, I was trying simple example to connect my UI with Database using Spring and Hibernate.
I am able to successfully call a method to fetch the data through my controller, service etc using REST.
But I am encountering below error,whenever I run the application.
Here "Feedback" is the name of Table in Database as well as the same name of my Pojo Java class.
Note : Giving different names to table and Java class also results in same error.
org.springframework.orm.hibernate3.HibernateQueryException: Feedback
is not mapped [from Feedback]; nested exception is
org.hibernate.hql.ast.QuerySyntaxException: Feedback is not mapped
[from Feedback]
Java Pojo:-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Feedback")
public class Feedback {
private int id;
private String title;
private String content;
private String name;
#Id
#GeneratedValue
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="title", nullable=false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="name", nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Feedback [id=" + id + ", title=" + title + ", content="
+ content + ", name=" + name + "]";
}
}
FeedbackDAO :-
#Repository
public class FeedbackDAO implements IFeedbackDAO {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#SuppressWarnings("unchecked")
public List<Feedback> getFeedbackList() {
// This line causes that error.
return hibernateTemplate.find("from Feedback");
}
...
...
}
Configuration made in db-config.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
What could be causing this ?
Do am I missing something here ?
Thanks
You might have missed a thing in sessionFactory definition.
<bean id="sessionFactory" ...>
...
<property name="annotatedClasses">
<list>
<value><java package name here>.Feedback</value>
</list>
</property>
...
</bean>

XML binding with the use of JAXB and Spring-MVC

the following xml is in a repository on a server:
<author xmlns="http://www..." xmlns:atom="http://www.w3.org/2005/atom">
<name>S. Crocker</name>
<address>None</address>
<affiliation></affiliation>
<email>None</email>
</author>
My model class:
#XmlRootElement(name = "author", namespace="http://www...")
#XmlAccessorType(XmlAccessType.FIELD)
public class Author {
#XmlAttribute(name="author")
private String author;
#XmlElement(name="name")
private String name;
#XmlElement(name="address")
private String address;
#XmlElement(name="affiliation")
private String affiliation;
#XmlElement(name="email")
private String email;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
According to a tutorial i saw i should use the #XmlSchema to a package-info.java
I create a class package-info.java but i don't know how to treat this.
Actually my problem is that i don't know how to use the corect annotations to bind the xml with the model class. The whole story is that i'm trying to retrieve an XML document from a repository, but i take null values. The problem as i saw here: JAXB: How to bind element with namespace
is that i don't use the correct annotations. Does anyone knows which are the correct annotations and how should i use them?
Below is an example of how you could map this use case:
package-info
I would use the package level #XmlSchema annotation to specify the namespace qualification. Specify the namespace to be your target namespace ("http://www.../ckp"). You want this namespace applied to all XML elements so specify elementFormDefault=XmlNsForm.QUALIFIED. The use xmlns to asssociate prefixes with your namespace URIs.
#XmlSchema(
namespace="http://www.../ckp",
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns={
#XmlNs(prefix="", namespaceURI="http://www.../ckp"),
#XmlNs(prefix="atom", namespaceURI="http://www.w3.org/2005/atom"),
}
)
package forum10388261;
import javax.xml.bind.annotation.*;
Author
Below is what your Author class would look like. I have removed the unnecessary annotations (annotations that were equivalent to the default mapping).
package forum10388261;
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Author {
#XmlAttribute
private String author;
private String name;
private String address;
private String affiliation;
private String email;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Demo
package forum10388261;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Author.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10388261/input.xml");
Author author = (Author) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(author, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<author xmlns:atom="http://www.w3.org/2005/atom" xmlns="http://www.../ckp">
<name>S. Crocker</name>
<address>None</address>
<affiliation></affiliation>
<email>None</email>
</author>
For More Information
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
I've never needed to use the namespace parameter on #XmlRootElement, try leaving that off; also, you have #XmlAttribute specified for author, but there's no author in your example besides the tag name.
As for:
Actually my problem is that i don't know how to use the corect
annotations to bind the xml with the model class.
In your spring config you can do:
<oxm:jaxb2-marshaller id="jaxb2Marshaller">
<oxm:class-to-be-bound name="com.mycompany.Author"/>
<!-- ... -->
</oxm:jaxb2-marshaller>
Then inject the jaxb2Marshaller directly or use a MessageConverter like so:
<bean id="xmlConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg>
<ref bean="jaxb2Marshaller"/>
</constructor-arg>
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="xml"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>
If you want to use spring's content negotiation, you could then use AnnotationMethodHandlerAdapter with the message converter:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="xmlConverter"/>
<!-- other converters if you have them, e.g. for JSON -->
</list>
</property>
</bean>

Categories

Resources