Newsletter

Example On Spring Dependency In The Form Of Objects

Spring » on Aug 7, 2011 { 42 Comments } By Sivateja

Let us see one example for previous concept, dependency in the form of objects with <ref /> element

files required..

i am taking complete pojo / poji model this time, And mates this isΒ  ” very important and Exact concept of spring framework ” , make sure you understood this application from start to end point, if you are not able to understand you may not able to continue with the remaining concepts πŸ™‚

i will try to explain clearly in my own way….

  • Journey.java
  • Travel.java
  • Vehicle.java
  • Car.java
  • Bus.java
  • spconfig1.xml
  • spconfig2.xml
  • ClientLogic.java

Journey is the interface, and Traveler is the implemented class

 

Journey.java

public interface Journey
{
   void startJournty();
}

Travel.java

public class Travel implements Journey
{
   Private Vehicle v;
   public void setV(Vehicle v)
   {
       this.v = v;
   }

   public void startJorunty()
   {
      System.out.println("Journey been started....");
      v.move();
   }
}

 


Vehicle
is the interface, Car and Bus are the implemented classes

See Traveler Class is depends on Vehicle object

Vehicle.java

public interface Vehicle
{
    void move();
}

Car.java

package java4s;

public class Car implements Vehicle{

	private String fuelType;
	private int maxSpeed;

	public String getFuelType() {
		return fuelType;
	}

	public void setFuelType(String fuelType) {
		this.fuelType = fuelType;
	}

	public int getMaxSpeed() {
		return maxSpeed;
	}

	public void setMaxSpeed(int maxSpeed) {
		this.maxSpeed = maxSpeed;
	}	

	public void move()
	{
		System.out.println("Fuel type :" +fuelType);
		System.out.println("max speed :" +maxSpeed);
		System.out.println("car started....");
	}

}

Bus

package java4s;

public class Bus implements Vehicle{

	private int maxSpeed;	

	public int getMaxSpeed() {
		return maxSpeed;
	}

	public void setMaxSpeed(int maxSpeed) {
		this.maxSpeed = maxSpeed;
	}	

	public void move()
	{
		System.out.println("max speed :" +maxSpeed);
		System.out.println("Bus started....");
	}

}

spconfig1.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="id1" class="java4s.Car">

<property name="fuelType" value="Diesel" />
<property name="maxSpeed" value="100" />

</bean>

<bean id="id2" class="java4s.Bus">
<property name="maxSpeed" value="80" />
</bean>

</beans>

 

spconfig2.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="id3" class="java4s.Travel">

<property name="v">
<ref parent="id2" />
</property>

</bean>
</beans>

 

ClientLogic.java

package java4s;

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;

public class ClientLogic {

	public static void main(String[] args)
	{
		Resource res1 = new ClassPathResource("spconfig1.xml");
		BeanFactory factory1 = new XmlBeanFactory(res1);

		Resource res2 = new ClassPathResource("spconfig2.xml");
		BeanFactory factory2 = new XmlBeanFactory(res2,factory1);

		Object o = factory2.getBean("id3");
		Journey j = (Journey)o;

		j.startJourney();

	}

}

Explanation:

  • ClientLogic.java is our client application, i mean it contains our business logic
  • Journey, Vehicle are two interfaces in our application
  • No confusion, i have taken all the classes with some implementation, i will tell you the reason why… ?
  • Now come to the configuration files, i have been taken 2 configuration xml (for explaining local, parent, bean attribute concept πŸ™‚ )

Now see execution flow…………….

Actually we have 2 configuration files right, so in our client logic we need to define factory object two times [ ClientLogic.java, line numbers, 12,13 – 15,16 ].Β  In factory1 object, i have been taken spconfig1.xml [ ClientLogic.java, Line number 12 ], where Car,Bus classes been configured. factory2 knows factory1, as we included factory1 object in factory2 [ see line number 16, ClientLogic.java ]

Once we call id3 in ClientLogic.java, then spring container will move toΒ spconfig2.xml and checks, there property v depends on other class right, and we given parent=id2, then control move to spconfig1.xml and finds id2 –> creates Bus class object, and will send back that Bus object to our client program

According to our program Bus object will be injected into the Traveler finally and there after we will get it into client application, and we can change id2 to id1 in the spconfig2.xml for getting Car object, with our recompilation πŸ˜‰

Huuuu, mates hope you got what am saying, πŸ™‚

This is the complete POJO / POJI Model of spring, i will tell you why we need to take Interface for every class like above, you might have known with this example, but no problem i will rise this topic in the next sessions.

 

Output:

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

42 Responses to “Example On Spring Dependency In The Form Of Objects”
  1. vijay says:

    Hi..
    Your explanation is too good and as i am fresher it is so easy to learn from your site..

    But if you will provide previous and next option while reading every page for continuous reading then it will be great..

    Thanks a lot..
    Vijay.

  2. Java4s says:

    @Vijay

    Actually we thought this, but all of us doesn’t need all these topics right ? so we have given as index, some thing like..

    https://www.java4s.com/spring/index-spring-framework/

  3. Pavan says:

    Sir when i run this i am getting this error,
    Exception in thread “main” org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [java4s.Travel] for bean with name ‘id3’ defined in class path resource [spconfig2.xml]; nested exception is java.lang.ClassNotFoundException: java4s.Travel

  4. Java4s says:

    @Pavan

    Yeah sorry its my mistake, correct class name is Travel not Traveler(Which i have given, and corrected now) please check now it will works.

    Like this if you face any issues please download the application and test/compare in your local.

    Please let me know if you face any further issues ?

    • Amit Lodhi says:

      Sir I am facing some problem heere.

      Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [Travel] for bean with name 'id3' defined in class path resource [spconfig2.xml]; nested exception is java.lang.ClassNotFoundException: Travel
      at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1352)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
      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 SprPck1.ClientLogic.main(ClientLogic.java:17)
      Caused by: java.lang.ClassNotFoundException: Travel
      at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
      at org.springframework.util.ClassUtils.forName(ClassUtils.java:250)
      at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:394)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1397)
      at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1344)
      … 6 more

  5. Pavan says:

    Thank you sir…really good examples explained in each topics for freshers to remember each concepts..
    Sir,when wil be the JSP,servlet part complete…

  6. Anitha says:

    Hi,
    This site is very very useful and your explanation is so simple and intersting that helps to study further.
    Thanks a lot for your effort..
    Anitha Raj

  7. Java4s says:

    @Pavan

    You welcome.

    Hmm i cannot tell you the exact time frame regarding to completion of JSP,Servlet, but might be in less than 2 months.

    We will send you an E-Mail update once we started to post, be in touch with our facebook/twitter / E-mail NewsLetters.

  8. Java4s says:

    @Anitha

    Glad to hear that its helped you :-), please feel free to share our blog with your friends/colleagues.

  9. Hi,

    This site is very helpful who is new in java framework.

    Very thanks for the same.

    I have to study about spring web-mvc module please provide the same ASAP or tell me another site for spring web-mvc.

    Regards
    Pankaj Kalra
    9654083668

  10. Vidyasagar says:

    Nice piece of tutorial,
    thank you.

  11. vikram says:

    Hi,

    Your website is very easy to learn like anything it is just like reading newspaper as simple as that.Can you post the IBatis topics.

    Thanks,
    Vikram

  12. Ashok says:

    your explanation is good but lot of spelling mistakes are there just verify once in each and every page.

  13. Anil Gupta says:

    your explanation is very good even example is very good…thanks

  14. SriDharan says:

    Very Good Explanantion. Understand core concepts in beginning stage…Good work dude.

  15. Geetha says:

    Really Good Explaination!! Its very helpful for beginners to learn and explore.. Thank You java4s.. Keep it up..

  16. Arun says:

    Wao nice tutorial.I got my dreamed website.

  17. mohan says:

    you r really great its to clean and perfect and a real fact is that your explained such a complicated thing into pretty simple one ..!! thanks a lot..!!!!

  18. Rupesh+Vislawath says:

    sir im getting error at j.startJourney(). it says identifier expected after this token

  19. paveen says:

    Above given example shows some error.
    Can you check it out plz.

  20. balu says:

    Really great very nice explanation

  21. asss says:

    khup mast explanations…

  22. sumit says:

    really ausome..

  23. Vidya says:

    Thank you Java4s for nice example, can you please help me how to achieve this using applicationcontext instead of beanfactory as i am using mainlt the applicationcontext in most of the examples:
    ApplicationContext ctx = new ClassPathXmlApplicationContext(“object.xml”);
    ApplicationContext ctx = new ClassPathXmlApplicationContext(“object1.xml”);

    object and object1.xml are my config files, if you can explain the differnce b/w beanfacorty and applicationcontext . thank you.

  24. Biplav says:

    Thanku Sir awesome explaination…..

    It will be very nice of you if you include some complex examples with MVC so that it will be more effective to learn realtime scenarios…………
    Thanks a lot

  25. suhas h says:

    Hi siva,
    Its a fabulous job.

  26. kunal chaudhari says:

    hello sir ,

    first of all vary thanks for this tutorial.

    i have one little confusion that what we can do if we want to Map TWO BEAN in single property Tag of another BEAN as i define below in my WAY don’t mind and please give me solution

  27. June says:

    Absolutely awesome and very helpful. you make the concepts so easy to follow!!!

  28. Priyanka Sharma says:

    Hi! When I am using ref parent then I get following exception:

    Feb 11, 2016 2:59:41 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [springconfig1.xml]
    Feb 11, 2016 2:59:41 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [springconfig2.xml]
    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘id3’ defined in class path resource [springconfig2.xml]: Cannot resolve reference to bean ‘id2’ while setting bean property ‘v’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘id3’ defined in class path resource [springconfig2.xml]: Can’t resolve reference to bean ‘id2’ in parent factory: no parent factory available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:275)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:104)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1245)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at java4s.ClientlogicObjectInjection.main(ClientlogicObjectInjection.java:17)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘id3’ defined in class path resource [springconfig2.xml]: Can’t resolve reference to bean ‘id2’ in parent factory: no parent factory available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:261)
    … 13 more

    But if I do all the configuration in single file and use ref as local then it works final. Please help in resolving the issue.

  29. kshirod says:

    when i am executing the client logic program , i am getting the “java4s.Travel cannot be cast to java4s.Journey” error. please help me out.Quick response will be appreciated.

  30. UnderScore says:

    @kshirod
    Can you share your code. I just want to know why you are casting Travel class to Journey.
    you can contact me by sending mail to onlineunderscore@gmail.com

    @Priyanka Sharma
    Make sure that you have setter method for property “v” in Travel class
    Both configuration files should be in specified directory.

    you can contact me by sending mail to onlineunderscore@gmail.com

  31. vasu says:

    hi sir
    this is very usefull to me
    and i was getting very useful information of springs, but i need some more information with using jsp servlets aplication examples from your site,
    please provide examples what i need sir

  32. Raj says:

    Hi!

    I have a confusion!

    On the above code as you mention to call the Jurney Object (Interface) was right

    Object o = factory2.getBean(“id3″);
    Journey j = (Journey)o;

    (or)
    the below code is right. Because the ID=”id3” refere the Travel class only..,

    Object o = factory2.getBean(“id3”);
    Travel j = (Travel)o;

    please clarify me..,

  33. abhishek Kumar says:

    @ Vidya
    You can do it with ApplicationContext container also.
    Method 1st:
    ApplicationContext actx = new ClassPathXmlApplicationContext(“spconfig1.xml”);
    String[] config2 = {“spconfig2.xml”};
    ApplicationContext actx1 = new ClassPathXmlApplicationContext(config2 ,actx);
    Now you can get the bean on actx1.getBean(“id3”);

    Method 2nd:
    String[] XmlConfigFile = {“spconfig2.xml”,”spconfig1.xml” };
    ApplicationContext actx = new ClassPathXmlApplicationContext(XmlConfigFile);
    Now you can get the bean on actx.getBean(“id3”);

    But before going with method 2nd, we need to make a little bit change in “spconfig2.xml” file. Instead of writing we need to write .
    It will work.
    Thanks
    Abhishek Kumar

  34. Gopikumar S says:

    i am new to java , i need core java concepts from you

  35. Thangadurai says:

    At first thanks for the course. Its easy to understand. I have one problem related to the above example. if i change the dependent id as id1 instead of id2 in spconfig2.xml also leads to the same output. thats there is no change in output for both the cases!!

  36. Nikhil says:

    I Searching a good tutorial for spring from last few days and i find this website excellent And nice because everything you written in this website is from the scartch level everyone can easily understand and moreover your highligting important points with different colours and emoji
    thanks for creating such websites and i hope it should help more N more people.

  37. prangya says:

    I did the program same as like u explain.but i got exception.org.springframework.beans.factory.BeanDefinitionStoreException:
    can u help me

  38. Monika says:

    HI, Thanks for the simple explanation.

    Can u please provide navigation arrow on top of page also for easy access.

    Also, what if we have 3 config xml file.How can we decide which is parent of which xml file?

  39. Avinash Kumar says:

    very good explanation bro!!!

  40. sushma says:

    Hi so in this example are we creating two ioc containers? As you said Spring IOC container is called BeanFactory.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.