Thursday, 19 January 2023

Micronaut: Produce a bean from a field

We can produce a bean from a field using @Bean annotation.

 

Example

@Bean
@Named("dataSource1")
SqlDataSource sqlDataSource1 = new SqlDataSource("abc.com", "Krishna");

 

Remember below points while producing a bean from a field.

a.   only public or package protected fields are supported on non-primitive types.

b.   If the field is static, private, or protected a compilation error will occur.

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-produce-bean-from-field’.

 

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-produce-bean-from-field</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 SqlDataSource class.

 

SqlDataSource.java

package com.sample.app.model;

public class SqlDataSource {

	private String url;
	private String userName;

	public SqlDataSource(String url, String userName) {
		this.url = url;
		this.userName = userName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Override
	public String toString() {
		return "SqlDataSource [url=" + url + ", userName=" + userName + "]";
	}

}

Step 4: Define BeansFactory class.

 

BeansFactory.java

package com.sample.app.factories;

import com.sample.app.model.SqlDataSource;

import io.micronaut.context.annotation.Bean;
import io.micronaut.context.annotation.Factory;
import jakarta.inject.Named;

@Factory
public class BeansFactory {

	@Bean
	@Named("dataSource1")
	SqlDataSource sqlDataSource1 = new SqlDataSource("abc.com", "Krishna");

	@Bean
	@Named("dataSource2")
	SqlDataSource sqlDataSource2 = new SqlDataSource("def.com", "Ram");
}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.model.SqlDataSource;

import io.micronaut.context.ApplicationContext;
import io.micronaut.inject.qualifiers.Qualifiers;;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext applicationContext = ApplicationContext.run()) {
			SqlDataSource sqlDataSource1 = applicationContext.getBean(SqlDataSource.class,
					Qualifiers.byName("dataSource1"));
			SqlDataSource sqlDataSource2 = applicationContext.getBean(SqlDataSource.class,
					Qualifiers.byName("dataSource2"));

			System.out.println("sqlDataSource1 : " + sqlDataSource1);
			System.out.println("sqlDataSource2 : " + sqlDataSource2);
		}
	}
}

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-produce-bean-from-field-1-jar-with-dependencies.jar’ in project target folder.

$ ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-produce-bean-from-field-1-jar-with-dependencies.jar
micronaut-produce-bean-from-field-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-produce-bean-from-field-1-jar-with-dependencies.jar

$ java -jar ./target/micronaut-produce-bean-from-field-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.
sqlDataSource1 : SqlDataSource [url=abc.com, userName=Krishna]
sqlDataSource2 : SqlDataSource [url=def.com, userName=Ram]

You can download this application from this link.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment