Newsletter

Example On Spring Autowiring byType

Spring » on Feb 8, 2012 { 22 Comments } By Sivateja

Let us see an application on Spring Autowiring with byType, let me clear this confusion about byType,byName…

Avoid byType – byName confusion

In this case, spring framework attempts to find out a bean in the configuration file, whose id is matching with the property type to be wired.  If a bean found with class as property type then that class object will be injected into that property by calling setter injection.  If no class found then that property remains un-wired, but never throws any exception just like before.

Example On Spring Autowiring byType

Files required…

  • Book.java
  • Categories.java
  • ClientLogic.java
  • spconfig.xml

Book.java

package java4s;
public class Book {

    private String bookname;
    private int bookprice;
       
    public String getBookname() {
        return bookname;
    }
    public void setBookname(String bookname) {
        this.bookname = bookname;
    }
    public int getBookprice() {
        return bookprice;
    }
    public void setBookprice(int bookprice) {
        this.bookprice = bookprice;
    }
           
}

Categories.java

package java4s;
public class Categories {

       private String name;
       private Book bk;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Book getBk() {
        return bk;
    }

    public void setBk(Book bk) {
        this.bk = bk;
    }

    public void show()
    {
        System.out.println("Categories name :"+name);
        System.out.println("Book name :"+bk.getBookname()+" and Book Price :"+bk.getBookprice());
    }
        

}

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 res = new ClassPathResource("spconfig.xml");
        BeanFactory factory = new XmlBeanFactory(res);
        
        Object o = factory.getBean("id1");
        Categories wb = (Categories)o;
        
        wb.show();
        
    }

}

spconfig.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.Categories" autowire="byType">
      <property name="name" value="General Books" />
  </bean>
  <bean id="SomeThing" class="java4s.Book">
      <property name="bookname" value="The Kids" />
      <property name="bookprice" value="300" />
  </bean>         
</beans>

Notes: We called id1 from ClientLogic.java [line number 15], and in spconfig.xml we have written autowire=byType, so first spring container will checks for the bean with class attribute Book [as autowire=byType and we have written private Book bk in Categories.java  ] and then inserts Book class properties into Book class object [ jav4s.Book ] and gives this book class object to Categories then injects value “General Books” into name property of Categories class.  [ read slowly 2 or 3 times, nothing is there friends ]

Finally in ClientLogic.java we used to type cast to get our output.

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

22 Responses to “Example On Spring Autowiring byType”
  1. Sarang says:

    Very nice tutorial for beginners.. Thanks a lot 🙂

  2. krish says:

    Super very nice Explanation….If we give for WebServices also…I will appreciate to your team…. Thanking you in advance….

  3. omg you clear my confution what am expected exactly super i dont know how can i thankq anyway you peoples doing great job .

  4. Rajashekar says:

    Sir in your given program.I got NullPointerException when Iam trying to give autowire=”constructor” can you pleas what is the reason

  5. Navya says:

    I hope in the XML id of second bean must be the name of the Class instead something,if it is something Can u please provide the explanation for that.

  6. Andreas Papandreas says:

    very doog explanation, you need definitelly continue your tutorials

  7. rambo says:

    very good explanation.. pls give more on XML dependencies

  8. sumit says:

    in 2nd bean “id=Book” rather than “id=something”

  9. srikanth says:

    Hi
    very good explanation about autowiring concept byType,
    but i have a doubt.
    As it is in explanation that when we configure autowire=”byType” it will check the class attribute with book name.
    but my doubt is like if we have more than one class attribute with same name Book
    but different package which one will it inject.
    can you please explain.

  10. Phani Kumar kolla says:

    Hi Srikanth,

    The above example clearly says that categories class is depending on book class object which is present in java4s package, not the other package.

    When factory.getBean(“id1”) is invoked, spring framework will execute the below code.

    Categories catObj = new Categories();
    catObj.setName(“XXXX”);
    Book bk = new Book();//from java4s package only, not form other package
    bk.setXXX();
    bk.setXXX();

    I hope you understood the above. Even if you have same class in other package spring framework ignores it.

  11. Amar says:

    @Navya

    Similar question for me too initially, but later what i came to know is, it is not mandatory to use beanid=”Book” (it is also correct) instead we can use any other name for beanid.

    But in case of ByName beanid must match

  12. sundara pandian.K says:

    hi Rajashekar,
    That null pointer exception is not caused by spring autowiring. If the class is not found it simply assigns the null object it didn’t cause any exception. In this program we are calling the getter method using that null object (line no:26). Java normally cause null pointer exception when we try to access the null object. this is happening here.If you remove line:26 it executes fine. so, as per siva sir, if there is no class found spring simply assign null object it won’t cause any exception untill you are not try to accessing that null object.

  13. niharika says:

    Hi Team ,

    I still did not get clear picture for srikanth question i.e.,

    if we have more than one class attribute with same name Book
    but different package which one will it inject

  14. sursh says:

    Hi,
    I have been in search of tutorials for deep understanding
    after mkyong.com and codejava.net you are the one to write
    in depth article.

    Line by line explanation even mkyong does not provide it.
    Salute to your hard work brother.

  15. nath says:

    @ srikanth,

    if we have more than one class reference in Category bean, then your beans.xml should be with the following configuration.

  16. kumar says:

    when we do byType what will happen if we have two references for same object.

    letz say like

    in this for Book type it has two beans

    for which bean tag it will refer ?

  17. kranthi says:

    Thanks for explaining as step by step.
    But small correction in the config file. we have to declare bk instead of something in second bean definition.
    <bean id="bk" class="java4s.Book">

  18. govindh says:

    you have to change the bean id=BOOK instead of Something

  19. thanks for the awesome tutorial on autowiring

  20. Kanth says:

    Still in confusion byType.
    Why it is picked Book

  21. Hari babu says:

    Really a cool awesome explanation!

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.