Friday 13 September 2019

Spring boot: Inject ApplicationContext by implementing ApplicationContextAware interface


Step 1: Define a component that implements ApplicationContextAware interface.

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}


Step 2: Inject ‘ApplicationContextProvider’ object in application class and get the ApplicationContext from getApplicationContext() method of ApplicationContextProvider bean.
@Autowired
private ApplicationContextProvider contextProvider;

Employee emp1 = contextProvider.getApplicationContext().getBean("krishna", Employee.class);

Find the below working application.

Employee.java
package com.sample.app.model;

public class Employee {

	private int id;
	private String firstName;
	private String lastName;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public void print() {
		StringBuilder builder = new StringBuilder();
		builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
				.append(lastName).append("]");
		System.out.println(builder.toString());

	}

}


EmployeeConfiguration.java
package com.sample.app.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sample.app.model.Employee;

@Configuration
public class EmployeeConfiguration {

	@Bean("krishna")
	public Employee newEmployee1() {
		Employee emp = new Employee();
		emp.setId(1);
		emp.setFirstName("Krishna");
		emp.setLastName("Majety");
		return emp;
	}
	
	@Bean("ram")
	public Employee newEmployee2() {
		Employee emp = new Employee();
		emp.setId(2);
		emp.setFirstName("Ram");
		emp.setLastName("Gurram");
		return emp;
	}
}


ApplicationContextProvider.java
package com.sample.app.providers;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}


App.java
package com.sample.app;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.model.Employee;
import com.sample.app.providers.ApplicationContextProvider;

@SpringBootApplication
public class App {

	@Autowired
	private ApplicationContextProvider contextProvider;

	public static void main(String args[]) {
		SpringApplication.run(App.class, args);
	}

	@Bean
	public CommandLineRunner demo() {
		return (args) -> {

			Employee emp1 = contextProvider.getApplicationContext().getBean("krishna", Employee.class);

			Employee emp2 = contextProvider.getApplicationContext().getBean("ram", Employee.class);

			emp1.print();
			emp2.print();

		};
	}

}

application.properties
logging.level.root=WARN


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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springcore</groupId>
	<artifactId>springcore</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
	</parent>


	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

	</dependencies>

</project>


Total project structure looks like below.



Run App.java, you can see below messages in console.
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.6.RELEASE)

Employee [id=1, firstName=Krishna, lastName=Majety]
Employee [id=2, firstName=Ram, lastName=Gurram]

You can download complete working application from this link.


Previous                                                    Next                                                    Home

No comments:

Post a Comment