Newsletter |
Example On Spring Dependency In The Form Of Objects
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 .:: | ||
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.
@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/
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
@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 ?
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
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…
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
@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.
@Anitha
Glad to hear that its helped you :-), please feel free to share our blog with your friends/colleagues.
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
Nice piece of tutorial,
thank you.
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
your explanation is good but lot of spelling mistakes are there just verify once in each and every page.
your explanation is very good even example is very good…thanks
Very Good Explanantion. Understand core concepts in beginning stage…Good work dude.
Really Good Explaination!! Its very helpful for beginners to learn and explore.. Thank You java4s.. Keep it up..
Wao nice tutorial.I got my dreamed website.
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..!!!!
sir im getting error at j.startJourney(). it says identifier expected after this token
Above given example shows some error.
Can you check it out plz.
Really great very nice explanation
khup mast explanations…
really ausome..
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.
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
Hi siva,
Its a fabulous job.
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
Absolutely awesome and very helpful. you make the concepts so easy to follow!!!
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.
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.
@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
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
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..,
@ 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
i am new to java , i need core java concepts from you
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!!
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.
I did the program same as like u explain.but i got exception.org.springframework.beans.factory.BeanDefinitionStoreException:
can u help me
Place Spcongif1.xml and spconfig2.xml in src folder.
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?
very good explanation bro!!!
Hi so in this example are we creating two ioc containers? As you said Spring IOC container is called BeanFactory.