Friday, 13 January 2023

Micronaut: Restrict injectable types

When you inject a bean, the bean class and all interfaces it implements and super classes it extends from become injectable via Micronaut.

 

public interface Dog {

	String aboutMe();
}

@Singleton
@Named("myBullDog")
public class BullDog implements Dog {

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

}

 

In the above example, you can choose to inject either the interface Dog or the concrete implementation BullDog.

 

If you do not want to inject the concrete implementation (BullDog), then you can use the typed member of the @Bean annotation to limit the exposed types.

 

@Singleton
@Bean(typed=Dog.class)
public class BullDog implements Dog {

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

}

 

When you try to lookup for BullDog bean, Micronaut throws NoSuchBeanException.

BullDog bullDog = applicationContext.getBean(BullDog.class);

 

Above snippet throws below error.

io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [com.sample.app.models.BullDog] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
	at io.micronaut.context.DefaultBeanContext.resolveBeanRegistration(DefaultBeanContext.java:2805)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:1617)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:867)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:859)
	at com.sample.app.App.main(App.java:15)

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-limit-injectable-types-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-limit-injectable-types-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 class.

 

BullDog.java

package com.sample.app.models;

import com.sample.app.interfaces.Dog;

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

@Singleton
@Bean(typed=Dog.class)
public class BullDog implements Dog {

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

}

 

Step 5: Define main application class.

 

App.java

 

package com.sample.app;

import com.sample.app.interfaces.Dog;
import com.sample.app.models.BullDog;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {

			System.out.println("Trying to get the bean of BullDog");
			try {
				BullDog bullDog = applicationContext.getBean(BullDog.class);
				System.out.println(bullDog.aboutMe());
			} catch (Exception e) {
				e.printStackTrace();
			}

			System.out.println("\n\nTrying to get the bean of Dog");
			try {
				Dog dog = applicationContext.getBean(Dog.class);
				System.out.println(dog.aboutMe());
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
}

 

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-limit-injectable-types-demo-1-jar-with-dependencies.jar’ in project target folder.
$ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-limit-injectable-types-demo-1-jar-with-dependencies.jar
micronaut-limit-injectable-types-demo-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-limit-injectable-types-demo-1-jar-with-dependencies.jar
$java -jar ./target/micronaut-limit-injectable-types-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.
Trying to get the bean of BullDog
io.micronaut.context.exceptions.NoSuchBeanException: No bean of type [com.sample.app.models.BullDog] exists. Make sure the bean is not disabled by bean requirements (enable trace logging for 'io.micronaut.context.condition' to check) and if the bean is enabled then ensure the class is declared a bean and annotation processing is enabled (for Java and Kotlin the 'micronaut-inject-java' dependency should be configured as an annotation processor).
	at io.micronaut.context.DefaultBeanContext.resolveBeanRegistration(DefaultBeanContext.java:2805)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:1617)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:867)
	at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:859)
	at com.sample.app.App.main(App.java:15)


Trying to get the bean of Dog
Bull Dog

You can download this application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment