• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Autowiring byName Example

January 4, 2016 by javainterviewpoint Leave a Comment

We all know what is Autowiring in Spring,now lets take a look into Autowiring byName in this article. In this type of autowiring, Spring framework finds out a bean in the configuration file, whose bean id is matching with the property name.  If a bean is found with the bean id as the property name in the configuration file then Spring internally uses Setter Injection and the object will be injected. If no id is found then that property remains un-wired and never throws any exception.

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.1.1.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar
    spring-context-3.2.9.RELEASE.jar
    spring-expression-3.2.9.RELEASE.jar

  3. Create the Java classes Bean1.java, Bean2.java and ClientLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Bean1.java

Bean1 class will have Bean2 class as a property(b2) and will have its corresponding getters and setters. It also has show() method which in-turn calls the disp() method of the Bean2 class. Value for b2 will be set through the configuration file using autowiring

package com.javainterviewpoint;

public class Bean1 
{
    public Bean2 b2;

    public Bean2 getB2() {
		return b2;
	}

	public void setB2(Bean2 b2) {
		this.b2 = b2;
	}

	public void show()
    {
    	System.out.println("Bean1 show() method called");
    	b2.disp();
    }
}

Bean2.java

Bean2 class has nothing but a single disp() method which will be called from Bean1 class.

package com.javainterviewpoint;

public class Bean2 
{
	public void disp()
	{
		System.out.println("Bean2 disp() method called");
	}
}

SpringConfig.xml

In our configuration file we have defined seperate id for each bean Bean1 and Bean2 classes

<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="b1" class="com.javainterviewpoint.Bean1" autowire="byName"></bean>
 
    <bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
</beans>
  • We mentioned autowire to byName while declaring Bean1, it actually searches for the property (b2) in Bean1  class and matching bean id in the configuration file if found then the object(Bean2 – b2) will be injected.
    <bean id="b1" class="com.javainterviewpoint.Bean1" autowire="byName"></bean>
     
        <bean id="b2" class="com.javainterviewpoint.Bean2"></bean>
    

ClientLogic.java

package com.javainterviewpoint;

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[])
    {
        //Read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read all the bean definition
        BeanFactory bf = new XmlBeanFactory(resource);
        //Get the Bean1 instance
        Bean1 bean1 = (Bean1)bf.getBean("b1");
        //Lets call the show() method
        bean1.show();
    }
}
  • Resource class reads our Configuration File(SpringConfig.xml)
  • BeanFactory class read all the bean definition mentioned in the config file.
  • Get the Bean1 Class instance by calling the getBean() method over the bean factory.
  • The String passed to getBean() method should be equivalent to the id defined in the SpringConfig.xml
  • Now call the show() method of the Bean1 class, which inturn calls the disp() method of Bean2 class. As Bean2 object will be injected automatically using autowiring byName.

Output

Once we run our ClientLogic.java we will get the below output

Bean1 show() method called
Bean2 disp() method called

Other interesting articles which you may like …

  • How to Create and Configure Beans in the Spring IoC Container
  • Spring Constructor Injection – Resolving Ambiguity
  • How to create Spring Beans Using Spring FactoryBean
  • How to specify Spring Bean Reference and Spring Inner Bean
  • Spring Dependency Checking and Spring @Required Annotation
  • Spring Autowiring using Annotation – @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Spring Bean Creation – Static Factory Method & Instance Factory Method
  • Spring PropertyPlaceholderConfigurer Example
  • Spring JdbcTemplate Example + JdbcDaoSupport
  • Spring CRUD Example with JdbcTemplate + Maven + Oracle
  • How to lazy initialize Spring beans?
  • How to change Spring Context Configuration file name

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: Autowiring, Autowiring byName Example, byName, Spring

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·