DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Frameworks
  4. Pragmatic Look at Method Injection

Pragmatic Look at Method Injection

Shekhar Gulati user avatar by
Shekhar Gulati
·
Jul. 05, 10 · Interview
Like (2)
Save
Tweet
Share
33.24K Views

Join the DZone community and get the full member experience.

Join For Free
Intent
Allows container to inject methods instead of objects  and provides dynamic sub classing.

Also Known As
Method decoration (or AOP injection)

Motivation
Sometimes it happens that we need to have a factory method in our class which creates a new object each time we access the class. For example, we might have a RequestProcessor which has a method called process which takes a request as an input and returns a response as an output. But, before the response is generated, request needs to be validated and then passed to a service class which will process the request and returns the response.
public class RequestProcessor implements Processor {

private Service service;

public Response process(Request request) {
Validator validator = getNewValidatorInstance();
List errorMessages = validator.validate(request);
if (!errorMessages.isEmpty()) {
throw new RuntimeException("Validation Error");
}
Response response = service.makeServiceCall(request);
return response;
}

protected ValidatorImpl getNewValidatorInstance() {
return new ValidatorImpl();
}

}

As can be seen in the above code snippet, we are creating a new ValidatorImpl instance each time process method is called. RequestProcessor requires a new instance each time because Validator might have some state which should be different for each request(for example a list of error messages).
RequestProcessor bean is managed by dependency injection container like spring where as Validator is being instantiated within the RequestProcessor. This solution looks like ideal but it has few shortcomings :
  1. RequestProcessor is tightly coupled to the Validator implementation details.
  2. If  Validator had any constructor dependencies, then RequestProcessor need to know them also. For example, if Validator has a dependency on some Helper class which is injected in Validator constructor then RequestProcessor needs to know about helper also.

There is also another approach that you can take in which container will manage the Validator bean(prototype) and you can make bean aware of the container by implementing ApplicationContextAware interface.
public class RequestProcessor implements Processor,ApplicationContextAware {

private Service service;
private ApplicationContext applicationContext;

public Response process(Request request) {
Validator validator = getNewValidatorInstance();
List errorMessages = validator.validate(request);
if (!errorMessages.isEmpty()) {
throw new RuntimeException("Validation Error");
}
Response response = getService().makeServiceCall(request);
return response;
}

protected Validator getNewValidatorInstance() {
return (Validator)applicationContext.getBean("validator");
}

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

public void setService(Service service) {
this.service = service;
}

public Service getService() {
return service;
}

}


This approach also has its drawback as the application business logic is now coupled with Spring framework.
Method injection provides a better way to handle such cases. The key to Method injection is that the method can be overridden to return the another bean in the container.In Spring method injection uses CGLIB library to dynamically override a class.

Applicability
Use Method injection when
  • you want to avoid container dependency as we have seen in the second approach, in which you have to inject a non singleton bean inside a singleton bean.
  • you want to avoid subclassing. For example, suppose that RequestProcessor is processing two types of response and depending upon the the type of report , we use different validators. So, we can have subclass RequestProcessor and have Report1RequestProcessor which just provides the Validator required for Report1.

  • public class Report1RequestProcessor extends RequestProcessor {

    @Override
    protected Validator getNewValidatorInstance() {
    return new ValidatorImpl();
    }

    }

    public abstract class RequestProcessor implements Processor {

    private Service service;

    public Response process(Request request) {
    Validator validator = getNewValidatorInstance();
    List errorMessages = validator.validate(request);
    if (!errorMessages.isEmpty()) {
    throw new RuntimeException("Validation Error");
    }
    Response response = getService().makeServiceCall(request);
    return response;
    }

    protected abstract Validator getNewValidatorInstance();

    public void setService(Service service) {
    this.service = service;
    }

    public Service getService() {
    return service;
    }

    }


Implementation
Method injection provides a cleaner solution. Dependency Injection container like Spring will override getNewValidatorInstance() method and your business code will be independent of both the spring framework infrastructure code as well as Concrete implementation of Validator interface. So, you can code to interface.
public abstract class RequestProcessor implements Processor {

private Service service;

public Response process(Request request) {
Validator validator = getNewValidatorInstance();
List errorMessages = validator.validate(request);
if (!errorMessages.isEmpty()) {
throw new RuntimeException("Validation Error");
}
Response response = getService().makeServiceCall(request);
return response;
}

protected abstract Validator getNewValidatorInstance();

public void setService(Service service) {
this.service = service;
}

public Service getService() {
return service;
}

}

The method requires a following signature
<public|protected> [abstract] <return-type> methodName(no-arguments);

If the class does not provide implementation as in our class RequestProcessor, Spring dynamically generates a subclass which implements the method otherwise it overrides the method. 
application-context.xml will look like this
<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-2.5.xsd">

<bean id="service" class="com.shekhar.methodinjection.ExampleService" />

<bean id="requestProcessor" class="com.shekhar.methodinjection.RequestProcessor">
<property name="service" ref="service"></property>
<lookup-method bean="validator" name="getNewValidatorInstance"/>
</bean>

<bean id="validator" class="com.shekhar.methodinjection.ValidatorImpl" scope="prototype">
</bean>
</beans>
This is how method injection can be used in our applications.

Consequences

Method injection has following benefits:
1) Provides dynamic subclassing
2) Getting rid of container infrastructure code in scenarios where Singleton bean needs to have non singleton or prototype bean.

Method injection has following Liabilities :
1) Unit testing - Unit testing will become difficult as we have to test the abstract class. You can avoid this by making the method which provides you the instance as non-abstract but that method implementation will be redundant as container will always override it.
2) Adds magic in your code - Anyone not familiar with method injection will have hard time finding out how the code is working. So, it might make your code hard to understand.
Dependency injection Spring Framework

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Building the Next-Generation Data Lakehouse: 10X Performance
  • The Power of Zero-Knowledge Proofs: Exploring the New ConsenSys zkEVM
  • Authenticate With OpenID Connect and Apache APISIX
  • A Beginner's Guide to Infrastructure as Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: