Method injection with Spring using Lookup method property

Spring Method Injection

In this article we will discuss how spring lookup-method annotation used for the method injection. Spring could inject dependencies between the beans in the application by following way of injection types:

  1. Setter Injection
  2. Constructor Injection
  3. Field Injection (@Autowired at field)
  4. Method Injection

As discussed in earlier article Spring Beans have mainly two types of scope i.e 1. Singleton (Instantiate only one object) and 2. Prototype (Instantiate a new object every time). To find more about Spring Bean Scope before reading this article. In Spring application there are many beans injected to each other for a goal. There is no problem when injected beans have same scope of beans like singleton bean injected with other singleton beans. Sometimes in Spring, Problems arise when you need to inject a prototype-scoped bean in a singleton-scoped bean. Since singletons are created (and then injected) during context creation it’s the only time the Spring context is accessed and thus prototype-scoped beans are injected only once, thus defeating their purpose.

But Spring provides another way for injection of beans, It is called method injection. It is solution of above problem in injecting different scoped beans. It works as that since singleton beans are instantiated at context creation, but it changes the way prototype-scoped are handled, from injection to created by an abstract method. It is actually a another kind of injection used for dynamically overriding a class and its abstract methods to create instances every time the bean is injected.

Method injection is different from Constructor Injection and Setter Injection. While in Constructor and Setter Injection, Spring creates the beans and injects them using the constructor or setter method, in Method Injection Spring overrides a given abstract method of an abstract class and provides an implementation of the overridden method.

Note there is an alternative to method injection would be to explicitly access the Spring context to get the bean yourself. It’s a bad thing to do since it completely defeats the whole Inversion of Control pattern, but it works.

This is an advanced form of dependency injection and should be used in very special cases as it involves byte-code manipulation by Spring.

Sample of Use Case of Spring Method Injection

You have a generic business object/singleton (TokenMachine) that need to create an implementation of an interface with state to perform some task.

Method injection with Spring using Lookup method property

There is usually one instance of Token Machine usually available in the Banks. However, a Token Machine generates a new instance of Token every time. In this case, Token Machine bean has scope Singleton while Token bean has scope Prototype.

In this sample application we define a Token class and an abstract TokenMachine class. The TokenMachine class defines an abstract method called generateToken() which returns a new Token. We use Spring’s Method Injection to create a new instance of Token from TokenMachine. We will configure Spring to override the generateToken() method and return a new instance of Token class.

Finally, we will test this sample by using Main class which will load the TokenMachine bean via Spring and invoke the generateToken() method.

Required Dependencies in Pom.xml

<properties>
  <spring.version>4.3.5.RELEASE</spring.version>
 </properties>
 
   <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>${spring.version}</version>
  </dependency>
 </dependencies>

Creating TokenMachine class for generating Token.
TokenMachine.java

/**
 * 
 */
package com.doj.app;

/**
 * @author Dinesh.Rajput
 *
 */
public abstract class TokenMachine {
 
 public void findToken(){
  System.out.println("Token has been generated "+generateToken());
 }
 public abstract Token generateToken();
 
}

TokenMachine contains the lookup-method tag with the name generateToken and bean id token that tells Spring to perform Method Injection on generateToken() method and return the Token type

Creating Token class for generating Token.
Token.java

/**
 * 
 */
package com.doj.app;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Component
@Scope("prototype")
public class Token {
 
}

Token is declared with scope Prototype so that a new instance is created for every call to generateToken() method.

Spring Configuration file
spring.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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
 <bean id="token" class="com.doj.app.Token" scope="prototype"/>
 
 <bean id="tokenMachine" class="com.doj.app.TokenMachine" scope="singleton">
  <lookup-method bean="token" name="generateToken"/>
 </bean>

</beans>

Finally, we need a java program to test the Method Injection setup. This is done by Main.java as below.

/**
 * 
 */
package com.doj.app.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.doj.app.TokenMachine;
import com.doj.app.config.AppConfig;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {
 public static void main(String[] args) {
  ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
  TokenMachine machine = context.getBean(TokenMachine.class);
  machine.findToken();
  machine = context.getBean(TokenMachine.class);
  machine.findToken();
  context.close();
 }
}

Now run this application main class has generation two times Token it always return different tokens.

Find Source Code from GitHub.

Spring JavaConfig’s approach

/**
 * 
 */
package com.doj.app.config;

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

import com.doj.app.Token;
import com.doj.app.TokenMachine;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@ComponentScan("com.doj.app")
public class AppConfig {
 @Bean 
 public TokenMachine tokenMachine(){
  return new TokenMachine(){

   @Override
   public Token generateToken() {
    return new Token();
   }
   
  };
 }
}

 

Spring Related Topics you may like

 

Previous
Next