I am learning DI and new to spring while trying out CI I have written following code and I think I am correct in syntax still it's showing bean creation error. why it is unable to create bean..??
The code is
Constuctor.java
package beans;
public class Constructor {
private String name;
private int age;
private String email;
public void Constructor(String name, int age, String email){
this.name=name;
this.age=age;
this.email=email;
}
public void show()
{
System.out.println("Name = "+name);
System.out.println("Age = "+age);
System.out.println("Email = "+email);
}
}
spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- Ordered parameters -->
<beans>
<bean id="t" class="beans.Constructor">
<constructor-arg value="Alok"/>
<constructor-arg value="24"/>
<constructor-arg value="alok#gmail.com"/>
</bean>
</beans>
Const_main.java
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Constructor;
public class Const_main {
public static void main(String[] args) {
ApplicationContext ap= new ClassPathXmlApplicationContext("resources/spring.xml");
Constructor c = (Constructor)ap.getBean("t");
c.show();
}
}
it's giving the following error
Jun 29, 2017 3:16:45 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#b1a58a3: startup date [Thu Jun 29 15:16:45 IST 2017]; root of context hierarchy
Jun 29, 2017 3:16:45 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resources/spring.xml]
Jun 29, 2017 3:16:46 PM org.springframework.context.support.ClassPathXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: **Error creating bean with name 't' defined in class path resource [resources/spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Exception in thread "main"** org.springframework.beans.factory.BeanCreationException: Error creating bean with name 't' defined in class path resource [resources/spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:240)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at test.Const_main.main(Const_main.java:10)
Try this way
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- Ordered parameters -->
<beans>
<bean id="t" class="beans.Constructor">
<constructor-arg>
<value>Alok</value>
</constructor-arg>
<constructor-arg>
<value>24</value>
</constructor-arg>
<constructor-arg>
<value>alok#gmail.com</value>
</constructor-arg>
</bean>
</beans>
You are trying to use Constructor Dependency Injection without creating any such constructor in your DTO (Constructor.java)
The method you defined above:
public void Constructor(String name, int age, String email){
this.name=name;
this.age=age;
this.email=email;
}
is just a simple method/function not a constructor, try to remove the word void.
Note:
To remove any ambiguities for constructor matching, it is more prefer to use indexes with constructor's parameters like:
<bean id="t" class="beans.Constructor">
<constructor-arg value="Alok" index="0"/>
<constructor-arg value="24" index="1"/>
<constructor-arg value="alok#gmail.com" index="2"/>
</bean>
Related
I am facing the below error while executing the below code.
I have my class names as below.
class Dad.java
package TestingDependecy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom) {
this.mom = mom;
}
public Dad (Child child) {
this.child = child;
}
public void name() throws IOException {
System.out.println("please enter a name ..");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
System.out.println("Please confirm your deatails below");
System.out.println("Your name is "+ name);
}
public void whichWork() {
mom.cooking();
}
public void mainWork() {
System.out.println("Don't distrub me Please...!!");
child.main();
}
}
class Mom.java
package TestingDependecy;
public class Mom {
public void cooking() {
System.out.println("I am cooking ");
System.out.println(" what else i can do ?");
}
}
Class Child
package TestingDependecy;
public class Child {
public void main() {
System.out.println("This is from child class");
}
}
Class Family.java
package TestingDependecy;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import TestingDependecy.Dad;
public class Family {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Dad d = context.getBean("dad", Dad.class);
d.mainWork();
System.out.println();
d.whichWork();
context.close();
}
}
Finally my ApplicationContext.xml file as below
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">
<!-- This is for family Package -->
<bean id = "mom"
class="TestingDependecy.Mom">
</bean>
<bean id = "child"
class="TestingDependecy.Child">
</bean>
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
I'm getting the below while executing the code.
Please find the error below.
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#1a1cd57: startup date [Fri May 04 08:45:01 IST 2018]; root of context hierarchy
May 04, 2018 8:45:02 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [ApplicationContext.xml]
May 04, 2018 8:45:02 AM org.springframework.context.support.AbstractApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dad' defined in class path resource [ApplicationContext.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
at TestingDependecy.Family.main(Family.java:13)
Please help me on this, what is the mistake I did here?
Regards,
Saikiran.
in ApplicationContext.xml you've passed two arguments to the constructor of dad bean :
<bean id = "dad"
class="TestingDependecy.Dad">
<constructor-arg ref="mom"/>
<constructor-arg ref="child"/>
</bean>
So you have to define a two-argument constructor in Dad class like this:
public class Dad {
private Mom mom;
private Child child;
public Dad (Mom mom, Child child) {
this.mom = mom;
this.child = child;
}
...
}
NOTE
all keep one constructor and corresponding bean constructor class
<bean id="e" class="com.test.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg> <ref bean="a1"/> </constructor-arg >
<constructor-arg> <ref bean="company"/> </constructor-arg>
</bean>
public Employee(int idx, String name, Address address, Company company) {
this.idx=idx;
this.name=name;
this.address=address;
this.company=company;
}
I have written a small code to check #Autowired annotation in Spring, here is my piece of code.
package beans;
//import org.springframework.beans.factory.annotation.AutoWired;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.beans.factory.annotation.*;
public class Car {
#Autowired
#Qualifier(value="e1")
private Engine engine;
//no need to have setters or constructors here
public void printData()
{
System.out.println("Engine model year: " +engine.getModelyear());
}
}
package beans;
public class Engine {
private String modelyear;
//generate setter and getter
public void setModelyear(String modelyear) {
this.modelyear = modelyear;
}
public String getModelyear() {
return modelyear;
}
}
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import beans.Car;
//import beans.Test;
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext ap = new ClassPathXmlApplicationContext("resource/spring.xml");
Car c=(Car)ap.getBean("c");
c.printData();
}
}
<!--spring.xml-->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- activate autowire annotation -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="engine" class="beans.Engine">
<property name="modelyear" value="2015"/>
</bean>
<bean id="e1" class="beans.Engine">
<property name="modelyear" value="2016"/>
</bean>
<bean id="c" class="beans.Car">
</bean>
</beans>
When I am trying to run Client.java class ,I am getting following error:
Can someone suggest why I am facing this issue?
Mar 11, 2017 10:19:24 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80: display name [org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80]; startup date [Sat Mar 11 10:19:24 IST 2017]; root of context hierarchy
Mar 11, 2017 10:19:24 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resource/spring.xml]
Mar 11, 2017 10:19:25 AM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext#70d18a80]: org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e
Mar 11, 2017 10:19:25 AM org.springframework.context.support.AbstractApplicationContext$BeanPostProcessorChecker postProcessAfterInitialization
INFO: Bean 'org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Mar 11, 2017 10:19:25 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e: defining beans [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,engine,e1,c]; root of factory hierarchy
Mar 11, 2017 10:19:25 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#18d1cf9e: defining beans [org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor,engine,e1,c]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'c': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private beans.Engine beans.Car.engine; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private beans.Engine beans.Car.engine; nested exception is java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
Caused by: java.lang.NoSuchMethodError: org.springframework.beans.factory.config.ConfigurableListableBeanFactory.resolveDependency(Lorg/springframework/beans/factory/config/DependencyDescriptor;Ljava/lang/String;Ljava/util/Set;Lorg/springframework/beans/TypeConverter;)Ljava/lang/Object;
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredElement.inject(AutowiredAnnotationBeanPostProcessor.java:361)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:61)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:414)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:249)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:155)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:246)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:291)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:122)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:66)
at test.Client.main(Client.java:13)
Set of jars which I am using are:
List of jars used and reference libraries while creating the project
I am beginner in spring java. I'm studying Autowiring but I found an error "Error creating bean with name 'theFirstTraveler' defined in class path resource." How to solve this error? Below my source code.
Thanks.
Regards,
Bobby
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="theFirstTraveler" class="com.tobuku.impl.Traveler">
<constructor-arg ref="car"/>
<property name="origin" value="Jakarta"/>
<property name="destination" value="Surabaya"/>
</bean>
<bean id="theSecondTraveler" class="com.tobuku.impl.Traveler">
<property name="car" ref="theOtherCar"/>
<property name="origin" value="Surabaya"/>
<property name="destination" value="Bandung"/>
</bean>
<bean id="theThirdTraveler" class="com.tobuku.impl.Traveler" autowire="byName">
<property name="origin" value="Bandung"/>
<property name="destination" value="Semarang"/>
</bean>
<bean id="theFourthTraveler" class="com.tobuku.impl.Traveler" autowire="constructor">
<property name="origin" value="Sukabumi"/>
<property name="destination" value="Jogja"/>
</bean>
<bean id="TheMercedes" class="com.tobuku.impl.Car">
<constructor-arg type="java.lang.String">
<value>Mercedes-Benz</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>S-Class S550 4MATIC</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>4.7L V8 Twin Turbocharger</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>Automatic 7-Speed</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>Gasoline</value>
</constructor-arg>
<property name="motion" value="My Human spirit is moving to the future..."/>
</bean>
<bean id="TheBmw" class="com.tobuku.impl.Car">
<constructor-arg type="java.lang.String">
<value>BMW</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>7 Series 740Li</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>3.0L I6</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>Automatic 8-Speed</value>
</constructor-arg>
<constructor-arg type="java.lang.String">
<value>Gasoline</value>
</constructor-arg>
<property name="motion" value="I am moving with pleasure. What an ultimate experience..."/>
</bean>
App.java
package com.tobuku.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.tobuku.impl.Traveler;
public class App
{
public static void main( String[] args )
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
// First Traveler
Traveler firstTraveler = (Traveler) context.getBean("theFirstTraveler");
System.out.println(firstTraveler);
firstTraveler.showCar();
firstTraveler.startJourney();
System.out.println("====================================================");
// Second Traveler
Traveler secondTraveler = (Traveler) context.getBean("theSecondTraveler");
System.out.println(secondTraveler);
secondTraveler.showCar();
secondTraveler.startJourney();
System.out.println("====================================================");
// Third Traveler
Traveler thirdTraveler = (Traveler) context.getBean("theThirdTraveler");
System.out.println(thirdTraveler);
thirdTraveler.showCar();
thirdTraveler.startJourney();
System.out.println("====================================================");
// Fourth Traveler
Traveler fourthTraveler = (Traveler) context.getBean("theFourthTraveler");
System.out.println(fourthTraveler);
fourthTraveler.showCar();
fourthTraveler.startJourney();
System.out.println("====================================================");
Vehicle carMercy = (Vehicle) context.getBean("TheMercedes");
Vehicle carBmw = (Vehicle) context.getBean("TheBmw");
System.out.println(carMercy);
carMercy.move();
System.out.println("-----------------------------------------------------------");
System.out.println(carBmw);
carBmw.move();
}
}
Traveler.java
package com.tobuku.impl;
import com.tobuku.common.Vehicle;
public class Traveler {
private Vehicle car;
private String origin;
private String destination;
public Traveler(){
origin = "";
destination
= "";
}
public Traveler(Vehicle car){
System.out.println("**** Constructor is called ****");
this.car = car;
}
public Vehicle getCar() {
return car;
}
public void setCar(Vehicle car) {
System.out.println("**** Setter is called ****");
this.car = car;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
#Override
public String toString(){
return "Traveler [origin=" + origin +
"; destination=" + destination + "]";
}
public void showCar(){
System.out.println(car);
}
public void startJourney(){
car.move();
}
}
Car.java
package com.tobuku.impl;
import com.tobuku.common.Vehicle;
public class Car implements Vehicle {
private String brand;
private String type;
private String engine;
private String transmission;
private String fuel;
private String motion;
public Car(){
brand = "";
type = "";
engine = "";
transmission = "";
fuel = "";
}
public Car(String brand, String type, String engine, String transmission, String fuel){
this.brand = brand;
this.type = type;
this.engine = engine;
this.transmission = transmission;
this.fuel = fuel;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getTransmission() {
return transmission;
}
public void setTransmission(String transmission) {
this.transmission = transmission;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public String getMotion() {
return motion;
}
public void setMotion(String motion) {
this.motion = motion;
}
public String toString(){
return "Car [brand=" + brand +
"; type=" + type +
"; engine=" + engine +
"; transmission=" + transmission +
"; fuel=" + fuel + "]";
}
public void move(){
System.out.println(motion);
}
}
Vehicle.java
package com.tobuku.common;
public interface Vehicle {
void move();
}
Log
Sep 05, 2016 11:29:56 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#4d405ef7: startup date [Mon Sep 05 23:29:56 ICT 2016]; root of context hierarchy
Sep 05, 2016 11:29:56 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Beans.xml]
Sep 05, 2016 11:29:56 PM org.springframework.context.support.ClassPathXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'theFirstTraveler' defined in class path resource [Beans.xml]: Cannot resolve reference to bean 'car' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'car' is defined
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'theFirstTraveler' defined in class path resource [Beans.xml]: Cannot resolve reference to bean 'car' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'car' is defined
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:648)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.tobuku.common.App.main(App.java:12)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'car' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:702)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1180)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 17 more
The problem is that you try to create bean which has a dependency that refer to Car but you don't have a bean with name like that. Try to give TheMercedes bean to theFirstTraveler. If this doesn't help please provide us the whole stack trace.
I am experimenting on "beforeAdvice" over "JointPoints" in spring aop. it's pretty simple i am calling target method. before executing target class method, before() method should execute.
ClientApp:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.nt.services.LoanApprover;
public class ClientApp {
public static void main(String[] args) {
//activate ioc container
ApplicationContext context = new FileSystemXmlApplicationContext("src/com/nt/cfgs/applicationContext.xml");
//get bean
LoanApprover approver = context.getBean("pfb",LoanApprover.class);
//call b.method
approver.approver();
}
}
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-4.0.xsd">
<bean id="auditAdvice" class="com.nt.aspect.MyBeforeAdvice" />
<bean id="target" class="com.nt.services.LoanApprover" />
<bean id="pfb" class="
org.springframework.aop.framework.ProxyFactoryBean ">
<property name="target" ref="target" />
<property name="interceptorNames">
<list>
<value>
auditAdvice
</value>
</list>
</property>
</bean>
</beans>
MyBeforeAdvice.java
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice{
#Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("I am in MyBeforeAdvice class");
}
}
LoanApprover.java
public class LoanApprover {
public void approver(){
System.out.println("I am in LoanApprover method");
}
}
when i run this application i am getting this exception.
Aug 13, 2015 12:16:04 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#7c6cd67b: startup date [Thu Aug 13 12:16:04 IST 2015]; root of context hierarchy
Aug 13, 2015 12:16:04 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [G:\java\Frameworks\SpringAOP\AOPProj3(Before Advice)\src\com\nt\cfgs\applicationContext.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pfb': FactoryBean threw exception on object creation; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '
auditAdvice
' is defined
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObject FromFactoryBean(FactoryBeanRegistrySupport.java:175)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFr omFactoryBean(FactoryBeanRegistrySupport.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanIn stance(AbstractBeanFactory.java:1517)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBe anFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractA pplicationContext.java:962)
at test.ClientApp.main(ClientApp.java:13)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '
auditAdvice
' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefi nition(DefaultListableBeanFactory.java:694)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBean Definition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(Abstract BeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBe anFactory.java:194)
at org.springframework.aop.framework.ProxyFactoryBean.initializeAdvisorChain(ProxyF actoryBean.java:460)
at org.springframework.aop.framework.ProxyFactoryBean.getObject(ProxyFactoryBean.ja va:244)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObject FromFactoryBean(FactoryBeanRegistrySupport.java:168)
... 6 more
please anyone tell me why i am getting this exception?
Simply change
<value>
auditAdvice
</value>
to
<value>auditAdvice</value>
It seems like spring is using whitespaces and newline symbols as ID here.
Further information on that topic is available here.
Hope that helps.
Getting Bean Creation error while refering prototype bean inside singleton bean please have a look in my following code snapshot
Sep 1, 2014 12:36:03 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#100ab23: startup date [Mon Sep 01 00:36:03 IST 2014]; root of context hierarchy
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5dcec6: defining beans [triangle,pointA,pointB,pointC,circle]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pointA' defined in class path resource [spring.xml]: 1 constructor arguments specified but no matching constructor found in bean 'pointA' (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:175)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:993)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:897)
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.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1087)
at org.koushik.javabrrians.Triangle.getPointA(Triangle.java:18)
at org.koushik.javabrrians.Triangle.draw(Triangle.java:46)
at org.koushik.javabrrians.DrawingApp.main(DrawingApp.java:26)
My Triangle class is like this
package org.koushik.javabrrians;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Triangle implements ApplicationContextAware {
private Point pointA;
private Point pointB;
private Point pointC;
ApplicationContext context = null;
public Point getPointA() {
//return pointA;
return (Point) context.getBean("pointA" , "Point.class");
}
public void setPointA(Point pointA) {
this.pointA = pointA;
}
public Point getPointB() {
//return pointB;
return (Point) context.getBean("pointB" , "Point.class");
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
//return pointC;
return (Point) context.getBean("pointC" , "Point.class");
}
public void setPointC(Point pointC) {
this.pointC = pointC;
// context.getBean("pointC");
}
public void draw() {
System.out.println("PoinA X = " + getPointA().getX() + " Y = " + getPointA().getY());
System.out.println("PoinB X = " + getPointB().getX() + " Y = " + getPointB().getY());
System.out.println("PoinC X = " + getPointC().getX() + " Y = " + getPointC().getY());
}
#Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
// TODO Auto-generated method stub
this.context = arg0;
}
}
My Circle Class is like this
package org.koushik.javabrrians;
public class Circle {
private Point centre;
public Point getCentre() {
return centre;
}
public void setCentre(Point centre) {
this.centre = centre;
}
public void draw() {
System.out.println("PoinA Centre = " + getCentre().getX() + " Y = " + getCentre().getY());
}
}
My Point Class is like this
package org.koushik.javabrrians;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
My Spring Configuration file is like this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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="triangle" class="org.koushik.javabrrians.Triangle" autowire = "byName" scope = "singleton">
</bean>
<bean id="pointA" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="0" />
<property name="y" value="0" />
</bean>
<bean id="pointB" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="-20" />
<property name="y" value="0" />
</bean>
<bean id="pointC" class="org.koushik.javabrrians.Point" scope = "prototype">
<property name="x" value="0" />
<property name="y" value="20" />
</bean>
<bean id="circle" class="org.koushik.javabrrians.Circle" scope = "prototype">
<property name="centre" ref="pointA" />
</bean>
</beans>
I am Getting following Error after execution
Sep 1, 2014 12:36:03 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#100ab23: startup date [Mon Sep 01 00:36:03 IST 2014]; root of context hierarchy
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Sep 1, 2014 12:36:03 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#5dcec6: defining beans [triangle,pointA,pointB,pointC,circle]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pointA' defined in class path resource [spring.xml]: 1 constructor arguments specified but no matching constructor found in bean 'pointA' (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:175)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:993)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:897)
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.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1087)
at org.koushik.javabrrians.Triangle.getPointA(Triangle.java:18)
at org.koushik.javabrrians.Triangle.draw(Triangle.java:46)
at org.koushik.javabrrians.DrawingApp.main(DrawingApp.java:26)
The immediate cause of the error is the quotes around "Point.class". Remove them (and you can also then remove the cast):
public Point getPointA() {
//return pointA;
return context.getBean("pointA" , Point.class);
}
(and similarly for the other methods). Your version is treated as a call to the varargs method getBean(String name, Object... args) where args are constructor arguments, and your Point class does not have a constructor taking a String parameter. Without the quotes it's a call to the non-varargs method getBean(String name, Class<T> type) where the second argument is the type of the bean you're retrieving.