Spring ApplicationContextAware Example

Spring provides ApplicationContextAware interface to get the ApplicationContext anywhere in our code. In order to get this feature we need to implement ApplicationContextAware interface in our beans and override setApplicationContext method.

Here is one example to get the context from CustomerGroup bean.

Customer.java

public class Customer {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Customer [name=" + name + "]";
    }


}

CustomerGroup.java

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

public class CustmerGroup implements ApplicationContextAware {
   
    ApplicationContext context;
    public ApplicationContext getContext() {
        return context;
    }

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

}

Application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
    <bean id="customer" class="com.pretech.test.Customer">
        <property name="name" value="Vinod Kumaran" />
    </bean>
    <bean id="customerGroupBean" class="com.pretech.test.CustmerGroup" />
</beans>

Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class AppContextMain {
 
    public static void main(String[] args) {
 
 
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
 
        CustmerGroup customerGroupBean = (CustmerGroup) context
                .getBean("customerGroupBean");
 
        //Getting context from customerGroup bean and getting customer from that context
        System.out.println(customerGroupBean.getContext().getBean(Customer.class));
    }
 
}

Output

Customer [name=Vinod Kumaran

Spring BeanNameAware Example

BeanNameAware Interface to be implemented by beans that want to be aware of their bean name in a bean factory. If a bean in spring implements BeanNameAware then that bean has to implement a method that is setBeanName. And when that bean is loaded in spring container, the name is set to this method.
Here is an example to implement this interface and printing the name when it is loaded.

 

Student.java (Which implements BeanNameAware)

import org.springframework.beans.factory.BeanNameAware;

public class Student implements BeanNameAware {
    @Override
    public void setBeanName(String name) {
        System.out.println("Setting bean name " + name);

    }

}

application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="student" class="com.pretech.test.Student" />
</beans>
Test class
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanNameAwareTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "application-context.xml");
    }
}
Output
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@48a930: defining beans [student]; root of factory hierarchy
Setting bean name student

Apache Camel Mongodb component Example

Apache camel provides many components to interact with external systems, here is one simple example to connect mongodb using from apache camel route.

Create a maven project and add below dependencies

<dependencies>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jetty</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-mongodb</artifactId>
            <version>2.12.1</version>
        </dependency>
    </dependencies>

 

Create a Camel route

package com.vinod.test;

import org.apache.camel.builder.RouteBuilder;

public class CamelMongoRoute extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("jetty:http://localhost:8181/mongoSelect")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=findAll");
        from("jetty:http://localhost:8181/mongoInsert")
                .to("mongodb:myDb?database=customerdb&collection=customer&operation=insert");
    }
}

Create application context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
    xsi:schemaLocation="
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

    <camel:camelContext id="camel-client">
        <camel:routeBuilder ref="vinodroute" />
    </camel:camelContext>
    <bean id="myDb" class="com.mongodb.Mongo">
        <constructor-arg index="0" value="localhost" />
    </bean>
    <bean id="vinodroute" class="com.vinod.test.CamelMongoRoute" />
</beans>

Create a Main program

This main program will start the routes

package com.vinod.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelMongoMain {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
                      new ClassPathXmlApplicationContext("application-context.xml");
    }

}
 

Run it

1. Start Mongodb
2. Run the main program
3. Use rest client to give inputs

To insert data into mongodb

Request body= {name:"Vinod K K"}
Response from mongodb = [{ "_id" : { "$oid" : "5419cefb0364771a127e352c"} , "name" : "Vinod K K"}]

Data in mongodb
> use customerdb
switched to db customerdb
> show collections
customer
system.indexes
> db.customer.find()
{ "_id" : ObjectId("5419cefb0364771a127e352c"), "name" : "Vinod K K" }
>


Done !!!!

Download example

Spring 4 AsyncRestTemplate Example

Spring's central class for asynchronous client-side HTTP access. Exposes similar methods as RestTemplate, but returns ListenableFuture wrappers as opposed to concrete results. See more about AsyncRestTemplate
1. Create a maven project with below dependencies 
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-core</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupid>org.springframework</groupid>
<artifactid>spring-web</artifactid>
<version>4.0.6.RELEASE</version>
</dependency>
2. Create a main class to test AsyncRestTemplate
import java.util.concurrent.ExecutionException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.AsyncRestTemplate;

public class AsyncRestTemplateExample {

public static void main(String[] args) {

String url = "http://pretechsol.com";
AsyncRestTemplate asyncRestTemplate = null;
HttpMethod method = null;
try {

// Create AsyncRestTemplate object
asyncRestTemplate = new AsyncRestTemplate();

// Define http method
method = HttpMethod.GET;

// Define response type
Class responseType = String.class;

// Define headers

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);

HttpEntity<String> requestEntity = new HttpEntity<String>("params",
headers);
ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate
.exchange(url, method, requestEntity, responseType);

ResponseEntity<String> entity = future.get();
System.out.println(entity.getBody());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

}

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts