Spring bean autowire by name

Autowiring by property name. This will inspect the application context and look for a bean named exactly the same as the property which needs to be autowired.

Let’s discuss spring bean autowire by name with below example. In below example we have SortNumbers class which have one dependency for sorting implementation. We use spring bean autowire by name here as we take bubbleSort as property name.

We are using spring boot here.

Example

SpringAutowiringApplication.java

package com.w3schools.SpringAutowiring;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
 
@SpringBootApplication
public class SpringAutowiringApplication {
        private static ApplicationContext appContext;
 
	public static void main(String[] args) {
		appContext = SpringApplication.run(SpringAutowiringApplication.class, args);
		sort(new int[]{ 31,22,13,43,15,6,37});
	}
 
	private static void sort(int[] data) {
		SortNumbers sortNumers = (SortNumbers) appContext.getBean("sortNumbers");
		sortNumers.sortNumbers(data);
	}
 
}

SortNumbers.java

package com.w3schools.SpringAutowiring;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class SortNumbers {
	@Autowired
	ISortAlgo bubbleSort;
 
	public void sortNumbers(int[] data){
		printNumbers(bubbleSort.sort(data));
	}
 
	private static void printNumbers(int[] data) {
        for (int i = 0; i < data.length; i++) {
            System.out.print(data[i]);
            if(i != data.length-1){
            	System.out.print(", ");
            }
        }
        System.out.println("\n");
    }
}

ISortAlgo.java

package com.w3schools.SpringAutowiring;
 
public interface ISortAlgo {
	public int[] sort(int[] data);
}

BubbleSort.java

package com.w3schools.SpringAutowiring;
 
import org.springframework.stereotype.Component;
 
@Component
public class BubbleSort implements ISortAlgo {
	@Override
	public int[] sort(int[] array) {
		int n = array.length;
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (array[i] > array[k]) {
                    swapNumbers(i, k, array);
                }
            }
        }
		return array;
	}
 
	private void swapNumbers(int i, int j, int[] array) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

Output

6, 13, 15, 22, 31, 37, 43

Related topics