Thursday, 5 January 2023

Micronaut: Qualify a bean by name

In this post, I am going to explain how to qualify a bean by name.

public interface Dog {

	String aboutMe();
}

@Singleton
public class BullDog implements Dog {

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

}

@Singleton
public class PoodleDog implements Dog {

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

}

@Singleton
public class DogService {

	private Dog dog1;
	private Dog dog2;

	public DogService (@Named("Bull") Dog dog1, @Named("Poodle") Dog dog2) {
		this.dog1 = dog1;
		this.dog2 = dog2;
	}
}

 

Above snippet defines

a. The Dog interface defines the common contract

b. The BullDog class is the first implementation

c. The PoodleDog class is the second implementation

 

public DogService (@Named("Bull") Dog dog1, @Named("Poodle") Dog dog2)

dog1 is injected with an instance of BullDog and dog2 is injected with an instance of PoodleDog.

 

 

How is this injection possible?

@Named("Bull") Dog dog1;

@Named qualifier value (Bull) + type being injected simple name (Dog) == (case-insensitive) == The simple name of a bean of type Engine (BullDog).

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-qualify-by-name’.

 

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-qualify-by-name</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 jakarta.inject.Singleton;

@Singleton
public class BullDog implements Dog {

	@Override
	public String aboutMe() {
		return "I am 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 "I am Poodle Dog";
	}

}

Step 5: DefineDogService class.

 

DogService.java

package com.sample.app.util;

import com.sample.app.interfaces.Dog;

import jakarta.inject.Named;
import jakarta.inject.Singleton;

@Singleton
public class DogService {

	private Dog dog1;
	private Dog dog2;

	public DogService(@Named("Bull") Dog dog1, @Named("Poodle") Dog dog2) {
		this.dog1 = dog1;
		this.dog2 = dog2;
	}

	public void aboutMe() {

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

	}

}

Step 6: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.util.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-qualify-by-name-1-jar-with-dependencies.jar’ in project target folder.

 

$ls ./target/
archive-tmp						maven-status
classes							micronaut-qualify-by-name-1-jar-with-dependencies.jar
generated-sources					micronaut-qualify-by-name-1.jar
maven-archiver						test-classes

 

Run the jar file by executing below command.

java -jar ./target/micronaut-qualify-by-name-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-qualify-by-name-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.
I am Bull Dog
I am Poodle Dog

 

You can download this application from this link.

 

Note

You can also declare @Named annotation at the class level of a bean to explicitly define the name of the bean.

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

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

}

@Singleton
@Named("myPoodlelDog")
public class PoodleDog implements Dog {

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

}

@Singleton
public class DogService {

	private Dog dog1;
	private Dog dog2;

	public DogService(@Named("myBullDog") Dog dog1, @Named("myPoodlelDog") Dog dog2) {
		this.dog1 = dog1;
		this.dog2 = dog2;
	}

	public void aboutMe() {

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

	}

}

 

  

Previous                                                    Next                                                    Home

Wednesday, 4 January 2023

Micronaut: Inversion of control hello world application

In this post, I am going to explain how can we manage a bean using Micronaut.

 

What is a bean?

A bean is a java object whose lifecycle (creation, execution and destruction) is managed by the Micronaut IoC container.

 

Since Micronaut implements ‘JSR-330: Dependency Injection for Java’, you can simply use the annotation in jakarta.inject package.

 

For example,

public interface Animal {

	String color();

	String owner();
}

@Singleton
public class Dog implements Animal{

	@Override
	public String color() {
		return "Black";
	}

	@Override
	public String owner() {
		return "Krishna";
	}

}

@Singleton
public class AnimalUtil {

	private Animal dog;

	public AnimalUtil(Animal dog) {
		this.dog = dog;
	}

	public void aboutMe() {

		System.out.println("Owner : " + dog.owner());
		System.out.println("Color: " + dog.color());

	}

}

 

Above snippet defines

a. Animal interface

b. A Dog implementation is defined and marked with Singleton scope.

c. The Animal is injected via constructor injection in AnimalUtil class.

 

How to perform dependency injection?

Get an instance of ApplicationContext.

ApplicationContext context = ApplicationContext.run();

 

'run' method run the ApplicationContext. This method will instantiate a new ApplicationContext and call start(). 'start()' method starts the application context.

 

Get an instance of AnimalUtil bean using getBean method.

AnimalUtil animalUtil = context.getBean(AnimalUtil.class);

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-ioc-hello-world’.

 

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-ioc-hello-world</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 Animal interface.

 

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

public interface Animal {

	String color();

	String owner();
}

 

Step 4: Define Dog and AnimalUtil classes.

 

Dog.java

 

package com.sample.app.models;

import com.sample.app.interfaces.Animal;

import jakarta.inject.Singleton;

@Singleton
public class Dog implements Animal{

	@Override
	public String color() {
		return "Black";
	}

	@Override
	public String owner() {
		return "Krishna";
	}

}

 

AnimalUtil.java

package com.sample.app.util;

import com.sample.app.interfaces.Animal;

import jakarta.inject.Singleton;

@Singleton
public class AnimalUtil {

	private Animal dog;

	public AnimalUtil(Animal dog) {
		this.dog = dog;
	}

	public void aboutMe() {

		System.out.println("Owner : " + dog.owner());
		System.out.println("Color: " + dog.color());

	}

}

 

Step 5: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.util.AnimalUtil;

import io.micronaut.context.ApplicationContext;

public class App {

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

 

Total project structure looks like below.



 

Run App.java, you will see below messages in the console.

Owner : Krishna
Color: Black

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-ioc-hello-world-1-jar-with-dependencies.jar’ in project target folder.

$ls ./target/
archive-tmp						maven-status
classes							micronaut-ioc-hello-world-1-jar-with-dependencies.jar
generated-sources					micronaut-ioc-hello-world-1.jar
maven-archiver						test-classes

Run the jar file by executing below command.

java -jar ./target/micronaut-ioc-hello-world-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-ioc-hello-world-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.
Owner : Krishna
Color: Black

You can download this application from this link.


 

At the time of writing this post, Micronaut supports the following types of dependency injection:

 

a.   Constructor injection (must be one public constructor or a single constructor annotated with @Inject)

b.   Field injection

c.    JavaBean property injection

d.   Method parameter injection

 

References

https://javax-inject.github.io/javax-inject/





 

 

 

 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Micronaut: Inversion of control tutorial

 

Micronaut: Inversion of control hello world application
Micronaut: Qualify a bean by name
Micronaut: Qualifying a bean By Annotation
Micronaut: Qualify a bean by annotation members
Micronaut: Specify a Primary bean using @Primary annotation
Micronaut: @Any: Inject any bean
Micronaut: inject a bean using @Inject annotation
Micronaut: @Factory: specify one or more bean implementations
Micronaut: Restrict injectable types
Micronaut : quick guide to built-in scopes
Micronaut: Initialize singleton beans parallely
Eager initialization of Singleton beans in Micronaut application
Micronaut: Specify custom scope on meta annotations
Micronaut: Produce a bean from a field
Micronaut: Produce a bean from primitive types
Micronaut: produce a bean from primitive array
Micronaut: Conditional beans using @Required annotation
Micronaut: Replace existing bean using @Replaces annotation
Micronaut: Replace a bean factory using @Replaces annotation
Micronaut : replace one or more factory methods but retain the rest?
Micronaut: replace default implementation of an interface
Micronaut: Bean life cycle methods
Micronaut: Publish and listen on custom events
Micronaut: define event listener using @EventListener annotation
Micronaut: Asynchronously listening for Events with @EventListener
Micronaut: Working with bean events
Micronaut: Introduction to Bean introspection api
Micronaut: @Introspected with @AccessorsStyle demo
Micronaut: Introspect public and package protected fields
Micronaut: Specify the constructor to use for introspection
Micronaut: introspection: static creator methods
Micronaut: Introspect enums
Micronaut: Introspect a compiled class
Mincronaut: read and write a property using BeanWrapper
Bean validations in Micronaut
Micronaut: Validate bean method parameters
Micronaut: Manually validate data class using Validator
Micronaut: Validate data classes using @Valid annotation
Micronaut: Custom constraint demo
Micronaut: How to import beans from other libraries?
How to configure log level of Micronaut application?
How to configure port and scheme for Micronaut application
How to configure log level of Micronaut application?
How to configure port and scheme for Micronaut application
How to configure maximum file upload size in Micronaut?
How to set context base path of Micronaut application?

Previous                                                    Next                                                    Home

PlantUML: Add comments to the diagram

Any line that starts with single quote (') is treated as comment.

 

comments.txt

@startuml

'-----------------------------------------------------
' Author : Krishna
' Date : 22-12-2022
' Client : Component is responsible to send
'		   the messages to server
' LoginServer : Server receive the messages
'				from client and process
' ADServer : Responsible to validate User credentials
'-----------------------------------------------------

Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials
ADServer -> LoginServer: Login Successful
LoginServer -> Client: Login Successful

@enduml

 

Above snippet generate below diagram.



 

Previous                                                    Next                                                    Home

Tuesday, 3 January 2023

Working with sequence diagram in PlantUML

Sequence diagram is an interaction diagram, that illustrates the sequence of messages between objects in an interaction.

 

For example, below diagram define the interactions between the components on a successful login flow.


Following snippet generate above diagram.

 

loginSuccessFlow.txt 

@startuml
Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials
ADServer -> LoginServer: Login Successful
LoginServer -> Client: Login Successful
@enduml

Points to note

a.   Arrow (->) is used to draw a message between two participants.

b.   Participants in the sequence diagram art not declared explicitly,

 


Previous                                                    Next                                                    Home

micronaut home page

 

Micronaut Home
1. Introduction to Micronaut
Introduction to Micronaut, setup the CLI, hello world applicaiton etc., Read more>>
2. Inversion of control tutorial
Explain how can we manage a bean using Micronaut. Read more>>
3. Micronaut Application configuration tutorial
Micronaut Application configuration tutorial Read more>>
4. Working with Aspects
Micronaut Aspects tutorial Read more>>
5. REST API Development
Micronaut REST API tutorial Read more>>