Home  >  Spring Core

Example of @Primary in Spring

By Arvind Rai, April 04, 2013
On this page we will provide example of @Primary in spring. @Primary annotation enables a bean that gets preference when more than one bean is qualified to autowire a single valued dependency. Suppose we have a super class or interface and it has some sub classes and all the subclasses are bean. Now in a class we have a setter method or property which is autowired for super class. In this case all the sub classes are eligible for dependency injection. And hence spring container will throw error because it is unable to select a bean for dependency injection because of more than one eligible candidate. In this case we can give preference to a bean using @Primary annotation on one sub class. Now this bean will be selected for the dependency injection. If we annotate two beans with @Primary annotation, again container will throw error. In XML, <bean> tag has primary attribute that can have true or false value. This is equivalent to @Primary annotation.

Create Component with @Primary

We have an interface and we will create two classes implementing that interface.
Animal.java
package com.concretepage;
public interface Animal {
	void displayName();
} 

Lion.java
package com.concretepage;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
@Component
@Primary
public class Lion implements Animal {
	@Override
	public void displayName() {
		System.out.println("--- Lion ---");
	}
} 

Tiger.java
package com.concretepage;
import org.springframework.stereotype.Component;
@Component
public class Tiger implements Animal {
	@Override
	public void displayName() {
		System.out.println("-- Tiger ---");
	}
} 

Dependency Injection

Find the class for dependency injection with @Autowired annotation.
AnimalService.java
package com.concretepage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AnimalService {
	private Animal animal;
	public Animal getAnimal() {
		return animal;
	}
	@Autowired
	public void setAnimal(Animal animal) {
		this.animal = animal;
	}
} 

Configuration and Main Method

AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages="com.concretepage")
public class AppConfig {
} 

SpringDemo.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringDemo {
	public static void main(String[] args) throws SQLException {
	    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	    ctx.register(AppConfig.class);
	    ctx.refresh();
	    Animal animal = ctx.getBean(Animal.class);
	    animal.displayName();
    	    ctx.registerShutdownHook();
	}
}  

Output

Case 1. As we have used @Primary annotation on Lion bean. This will be selected for dependency injection. Find the output.
--- Lion ---
 
Case 2. If we do not provide @Primary annotation on any bean, we will get error.
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.concretepage.Animal] is defined: expected single matching bean but found 2: lion,tiger
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) 
Case 3. If we provide @Primary annotation on both the bean, we will get error.
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.concretepage.Animal] is defined: more than one 'primary' bean found among candidates: [lion, tiger]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.determinePrimaryCandidate(DefaultListableBeanFactory.java:1183) 

Gradle File

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'SpringDemo'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.2.7.RELEASE'
} 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us