Sunday, 8 January 2023

Micronaut: Specify a Primary bean using @Primary annotation

In case of multiple interface implementations, we can specify the primary bean to be selected using Primary annotation.

 

Consider the following example:

public interface Dog {

	String aboutMe();
}

 

Dog interface is implemented by these classes.

@Singleton
public class BullDog implements Dog {

	@Override
	public String aboutMe() {
		return "Bull Dog";
	}

}

@Singleton
public class PoodleDog implements Dog {

	@Override
	public String aboutMe() {
		return "Poodle Dog";
	}

}

 

Let's refer the Dog implementation.

@Singleton
public class DogService {

	private Dog dog1;

	public DogService(Dog dog1) {
		this.dog1 = dog1;
	}

	public void aboutMe() {

		System.out.println(dog1.aboutMe());

	}

}

  As there are two Dog interface implementations possible, you will get 'DependencyInjectionException' like below.

 

Exception in thread "main" io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for parameter [dog1] of class: com.sample.app.service.DogService

Message: Multiple possible bean candidates found: [com.sample.app.models.BullDog, com.sample.app.models.PoodleDog]
Path Taken: new DogService(Dog dog1) --> new DogService([Dog dog1])

 

How to resolve this problem?

We can address this problem by making a bean as primary using Primary annotation.
@Singleton
@Primary
public class BullDog implements Dog {

	@Override
	public String aboutMe() {
		return "Bull Dog";
	}

}

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-primary-annotation-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-primary-annotation-demo</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.1</micronaut.version>

		<maven.compiler.target>15</maven.compiler.target>
		<maven.compiler.source>15</maven.compiler.source>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject-java</artifactId>
			<version>${micronaut.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>

				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

 

Step 3: Define Dog interface.

 

Dog.java
package com.sample.app.interfaces;

public interface Dog {

	String aboutMe();
}

 

Step 4: Define BullDog and PoodleDog classes.

 

BullDog.java
package com.sample.app.models;

import com.sample.app.interfaces.Dog;

import io.micronaut.context.annotation.Primary;
import jakarta.inject.Singleton;

@Singleton
@Primary
public class BullDog implements Dog {

	@Override
	public String aboutMe() {
		return "Bull Dog";
	}

}

 

PoodleDog.java

package com.sample.app.models;

import com.sample.app.interfaces.Dog;

import jakarta.inject.Singleton;

@Singleton
public class PoodleDog implements Dog {

	@Override
	public String aboutMe() {
		return "Poodle Dog";
	}

}

 

Step 5: Define DogService class.

 

DogService.java

package com.sample.app.service;

import com.sample.app.interfaces.Dog;

import jakarta.inject.Singleton;

@Singleton
public class DogService {

	private Dog dog1;

	public DogService(Dog dog1) {
		this.dog1 = dog1;
	}

	public void aboutMe() {

		System.out.println(dog1.aboutMe());

	}

}

 

Step 6: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.service.DogService;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext context = ApplicationContext.run()) {
			DogService animalUtil = context.getBean(DogService.class);
			animalUtil.aboutMe();
		}
	}
}

 

Total project structure looks like below.

 



 

Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-primary-annotation-demo-1-jar-with-dependencies.jar’ in project target folder.


$ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-primary-annotation-demo-1-jar-with-dependencies.jar
micronaut-primary-annotation-demo-1.jar
test-classes

 

Run the jar file by executing below command.

java -jar ./target/micronaut-primary-annotation-demo-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-primary-annotation-demo-1-jar-with-dependencies.jar
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Bull Dog

 

You can download this application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment