POSTing multipart requests with RestTemplate

Some days ago I had to write a little client application to call a RESTful web service; my job was to upload some data, defined in terms of JSON, along with a picture (PNG format, but that does not matter for this time). These tasks are usually carried out with POSTing form/multipart messages to the endpoint – my case was no different, the server was expecting just that. I thought it would be easy and fast to throw in RestTemplate from Spring, but as it turned out, this simple task took me around 12 hours, a complete Sunday and a lot of pain (finally, Sotirios Delimanolis pointed me in the right direction on StackOverflow.com). As it seems, there is little amount of code examples out there, so I thought I’d post one here.

Continue reading “POSTing multipart requests with RestTemplate”

Advertisements

Spring: injecting an enum conditionally

The other day I was working on a piece of legacy code, with old-fashioned xml based Spring injection. All of a sudden I found myself in a situation where I had to inject an enum, based on some condition specified in a .properties file. This is easy to do with Java config, but not so usual to me with XMLs, so I thought I’d put it here. Continue reading “Spring: injecting an enum conditionally”

Aspects for good, decoupled design

Basics

We’ve all learnt that good, object oriented design is based on some kind of layering of the concepts; one layer has a very well defined scope, like for example database access, presentation and the alike. A layer is not allowed to use any other layer, but the one and only the one  right below it. A typical such architecture would look something like the one on the following diagram (drawn with creately.com):

layer
Typical layered architecture

Every class to be written, is perfectly contained in one and only one layer. For example, the class UserDataConverter would probably be contained in layer “Data Conversion”; it has nothing to do with data access, for example, nor with displaying information.

The situation, however, gets completely different when dealing with requirements that are all over the system – like transactions or logging, for example. These things are spread in an application. They are not tied to a specific layer, but rather to all of the layers. If you want transaction management, that will possibly impact all the layers from the top to the bottom; you can’t do it in the DAO level alone. A transaction may start with a click on the GUI, and propagate all the way down to the database – should anything go wrong at any level, the transaction rolls back.

Let’s take an example: we want to perform some profiling, to measure the running time for some of our methods. These methods are not specific to any layer, they can be anywhere in our system, from the data access layer up to presentation. If we’d represent this feature on the diagram above, it could look something like this:

asp
Profiling feature breaks the boundaries of layers

We cannot say that profiling should apply to business logic alone, as we may as well want to know how many time does it take to convert data between different formats. Now, a very bad solution to this problem would be getting the current time in the beginning and the end of every method we want to be profiled, and doing something with the result. This solution would create some awful spaghetti code with lot of duplication, not to mention the tedious work one should be doing for a large, legacy system with hundreds of methods to be profiled.

A nicer option would be creating some kind of utility class, to which you could tell that the method has started executing, and has finished eventually. The utility would take care of computing the elapsed time and handling the resulting numbers. However, this would still be pretty tightly coupled, with two invocations per method.

public void longRunningMethod() {
  profiler.methodStarted();
  // ...
  profiler.methodFinished();
}

It may seem that we’ve now got rid most of the code multiplication, but those start/stop methods are still spread all around our code base. How do we clean up our code, then?

Aspects to the rescue

Thank God, there is a way to handle this situation (and of course not only this one; it’s also suitable for error handling, self-* operations, customized access management, and almost any feature that spans through layers): using aspects (as we will see, aspects are also called interceptors in some frameworks).

In order to understand how aspects actually work, let’s begin with examining method calls. A usual method call looks like this (obvious diagram to follow):

call
Ordinary method call

With the usage of aspects, this is slightly changed. The object on which the method is called, will be coated in a proxy object to which all the method calls will be routed. Whenever a method call is made to the proxy object, the call will be ‘hijacked’, and the proxy will be given a chance to perform different operations before, after or around (before+after) the method call. For this to work, you will need some kind of a container (either Spring or JavaEE can be a good choice) or third party library, as you cannot do this with Java right out of the box.

As you can see on the diagram above, the container directs the call of otherMethod to the proxy around object2, and performs some operations before and/or after the original method call. This way object2.otherMethod can always stay the same, the only things that change are the before and after methods, but as you are going to see, they are present at only one place within the whole system. The class that implements the logic for before and after is called the Aspect.

With such an aspect, the code for measuring elapsed times for methods can be totally decoupled from the rest of the application. We can come up with an aspect to hold logic that will be run around (remember, around = before+after) the method call:

public class LatencyTracerAspect {
    //...
    public void interceptAround() {
      //code for getting start time
      // run original, business method
      //code for measuring elapsed time
    }
}

All that remains, is to make the container notice our aspect, and tell it what methods to intercept. This is, nevertheless different for each and every container – see below for examples.

Simple, elegant, 100% reusable and totally independent of the business logic (single responsibility principle for the win).

 

Ups and downs of aspects

As mentioned earlier, aspects are very useful when some application requirements would break the boundaries of different layers. In these cases it’s best to organize these features such a way they are easily accessible everywhere, without code duplication – through aspects. However, it’s a very bad practice to extract pieces of business logic into aspects. A poorly implemented aspect with surprising side effects can be the best place for bugs to hide. It is perfectly OK to implement an aspect to check whether a certain XML file is well formed or not, before starting to work with it, but do not send back a reject message to the client from the aspect if the validation fails. Throw an unchecked exception instead, and let business logic handle functional requirements like sending reply messages.

Usually, using before or around aspects you can manipulate the parameters passed in to a method call; with after and around aspects you can modify the return values of the those methods intercepted. Even if it’s technically possible, (most of the times) it is not a good practice to do so. Again, figuring out that the system is throwing exceptions just because some aspect keeps changing the input parameters or the return values is, well, at least tedious and frustrating.

Don’t overuse aspects. Although many times they come in handy, they can make debugging a nightmare. Not to mention that normally aspects will not run with the unit tests suite (as there is no container present to interpret them), so watch out for logic hiding in them. Test them as well as your regular business objects.

 

Examples

As we know the theory by now, let’s apply this knowledge in practice. The code examples to follow are not meant to make you an aspects/interceptors expert, just to exemplify how the things mentioned above can be achieved with different containers. In the following, we are going to implement the profiling aspect using three different containers: Spring, EJB and CDI.

Spring

In Spring, each method to be intercepted should be contained in a Spring bean (note that only managed beans will be intercepted, not those created with the new keyword), and the same is true for the caller method. You cannot intercept a method call on a non-Spring-bean.

We are going to create an annotation, through which we will tell the container that we want our method intercepted. For this, we create a usual, nothing-fancy annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Profiled {

}

That’s it, the signaler annotation is done. Now, we shall create an aspect, and bind our annotation to it.No rocket science here, all we have to do is type in the following code:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class ProfilingAspect {

	@Around("@annotation(Profiled)")
	public Object intercept(ProceedingJoinPoint context) {
		Object retval = null;

		long start = System.nanoTime();

		try {
			retval = context.proceed();
		} catch (Throwable t) {
			// Some clever exception handling
		}

		long end = System.nanoTime();
		System.out.println("------------------------------");
		System.out.println("Profiling result: " + (end - start) + " nanos.");
		System.out.println("------------------------------");
		return retval;
	}
}

Notice the @Aspect annotation at the top of of the class. Don’t fall in a common trap here: in your config file, you still have to define this aspect as a bean; thus the @Aspect annotation alone is not enough. Also, in the config file (I am taking a stand on Java class based configuration) you have to enable AspectJ style proxying, using the  @EnableAspectJAutoproxy annotation. Finally, don’t forget to call proceed() on the context object, so the program flow can advance.

Also note the @Around(“@annotation(Profiled)”) annotation. The expression (aka Pointcut) tells Spring to intercept all methods annotated with @Profiled. So, let’s create a method that can be intercepted (probably the easiest part):

public class Intercepted {
	@Profiled
	public void sayIt(String name) {
		System.out.println("We're happy, " + name);
	}
}

Pretty simple, huh? From now on, every method annotated with @Profiled will be intercepted by the container, provided that these annotations are placed on managed beans’ public methods.

Note:

  • The container will not intercept private method calls.
  • Don’t forget to put aspectjveawer.jar on your classpath.
  • You can play around with the context object; you can even change what’s getting passed and returned from a method.
  • Method calls from within the same bean are not intercepted
  • You can read further on this topic here

JavaEE

EJBs

(Aspects are called Interceptors in the enterprise world) In this case, the implementation for the profiler is somewhat easier. As this is JavaEE, you don’t have to place different kinds of jars on the classpath, as your container will have everything needed – right out of the box.

We don’t have to create annotations here, as the binding is solved differently with EJBs. Our interceptor class is somewhat similar to the one before, and looks like this:

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class Interceptor {

	@AroundInvoke
	public Object intercept(InvocationContext context) {
		//Logic is the same as before...
	}
}

The binding in the EJB code is done using the @Interceptors annotation applied on EJB class level(in which case all public methods will be intercepted) or method level(only those annotated methods will be intercepted). Our intercepted bean/method will be nothing more than:

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Stateless
// @Interceptors(Interceptor.class) could have been declared here too
public class Intercepted {

    @Interceptors(Interceptor.class)
	public void sayIt(String name) {
		System.out.println("We're happy," + name);
	}
}

Note:

  • Internal method calls (within the same bean) are not intercepted, no matter how the methods are annotated.
  • Private methods (resulting from the bullet above) are not intercepted
  • You are free to have several interceptors for the same bean/method. Those interceptors have to be enumerated like this: @Interceptors({Interceptor1.class, Interceptor2.class})

CDI interceptors

In the case of CDI interceptors we need an intercepted bean, an interceptor, and an interceptor binding – which is just like in case of our Spring example, a custom annotation.

With the help of Interceptor Bindings, we can tell the container which methods should be intercepted. The interceptor binding is not much different from our first @Profiled annotation; we only need to add @InterceptorBinding to it:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.interceptor.InterceptorBinding;

@InterceptorBinding
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Profiled {
}

An interceptor will be annotated with @Interceptor as well as the annotation dealing with the interceptor binding – it is somewhat similar to a Spring pointcut.  This will bind our @Profiled annotation to the interceptor logic:

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

@Interceptor
@Profiled
public class CdiInterceptor {

	@AroundInvoke
	public Object around(InvocationContext context) throws Exception{
        //... Logic same as before ...
    }

The intercepted class is, again, the same as with Spring:

	@Profiled
	public void sayIt() {
		System.out.println("CDI bean for the win");
	}

Finally, we have to enable CDI and the interceptors too. By default, CDI is turned off, you can switch it on by placing an empty beans.xml file in your META-INF directory. This is not enough in our case, though. CDI interceptors are also disabled by default; in order to enable them, we will make our new interceptor class visible to CDI container using the same beans.xml:

<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
                         http://java.sun.com/xml/ns/javaee
                         http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

	<interceptors>
		<class>blog.intercept.CdiInterceptor</class>
	</interceptors>
</beans>

To read more in depth about CDI interceptors, go to: http://docs.jboss.org/weld/reference/1.0.0/en-US/html/interceptors.html.

Note:

  • Internal method calls (within the same bean) are not intercepted, no matter how the methods are annotated.
  • Private methods (resulting from the bullet above) are not intercepted

 

Conclusions

Aspects can be a very efficient and clean means of decoupling business logic from omnipresent features. This way the business methods can deal with business requirements while aspects add the decorator functionality for handling common, non-layer specific tasks.

Aspects are easy to get started with, as chances are high that larger systems are already based on either Spring or JavaEE. They both handle aspects (interceptors) very well, without writing complex code to enable them.

Aspects over-usage can have a bad impact on the system, as it can become hard to track what feature is handled by what aspect. Also, take care not to implement features carrying business value as aspects.

Constructor vs. Field injection

I was interviewing a candidate the other day; we were talking about Spring, when I asked him if he preferred constructor or field injection. Typically people pick a side; either the first or the second one, so I was pretty surprised when the candidate told me that it depends on the context. And actually, this is the most awesome answer (in my opinion, of course) one can give to this question.

A lot has already been written about this topic. Most of the articles (and several people I know) state that not injecting all your dependencies through the constructors you are doing it all wrong, as you are hiding your dependencies (This makes perfect sense, but only up to a certain limit). Do these people then actually say that you have no way to write code of good quality based on the EJB technology? There you cannot use constructor injection at all – since you must provide a no-arg constructor that will be called by the container. Can anybody say that every each such system is rubbish and should be thrown away? I’m quite positive that we could find awesome EJB systems without an exhaustive search.

On the other hand, however, in Spring you are free to inject anything through your constructors. Is it than the only one right way to do dependency injection? Should the field based option just left out starting from the next releases of the framework and buried forever?I’d say no – and not only for backwards compatibility reasons. There are many cases when constructor injection produces better results than field injection; but not always. 

Let’s just take two examples. In the first one we are producing the most awesome BDD framework ever. There is only one thing left for us to do, develop a reporting module that is capable of producing test results in various formats (XML, HTM and plain text, for example).  We can come up with something like this:


public class ReportHandler {

  private Reporter reporter;

  public ReportHandler(Reporter reporter) {
    this.reporter = reporter;
  }

  public ReportContents produceOutput() {
    //...
    reporter.getReport()
    //...
  }

  public void dumpOutput() {
    //...
    reporter.persistReport();
    //...
  }
  //...
}

Constructor based injection is clearly the right choice here. With field-based injection we couldn’t even decide what kind of reporter to inject – that is an another level of abstraction.

Let’s now suppose that we are writing a simple text parser utility; it needs to replace placeholders of format #{…} with actual values, replace end of line characters to Linux style and remove all lines that start with three stars. In this case these three responsibilities may very well be factored out to different classes. Now, we have two possibilities:

Nr. 1

public class Parser {

 public Parser(PlaceholderResolver resolver, EndingsReplacer replacer, CommentsDeleter deleter) {
   this. resolver = resolver;
   this.replacer = replacer;
   this.deleter = deleter;
 }

 public Text resolveProperties(...) {
   //...
   Text text = resolver.resolve(...);
   //...
 }

 public Text deleteComments(...) {
   //...
   Text text =  deleter.removeComments(...);
   //...
  }

 public Text replaceEndings(...) {
   //...
   Text text = replacer.replaceEndings(...);
   //...
 }
}

or Nr. 2

public class Parser {

 @Inject
 PlaceholderResolver resolver;
 @Inject
 EndingsReplacer replacer;
 @Inject
 CommentsDeleter deleter;

 
 public Text resolveProperties(...) {
   //...
   Text text = resolver.resolve(...);
   //...
 }

 public Text deleteComments(...) {
   //...
   Text text = deleter.removeComments(...);
   //...
  }

 public Text replaceEndings(...) {
   //...
   Text text = replacer.replaceEndings(...);
   //...
 }
}

The problem with the first version is that we are injecting dependencies through the constructor which are not really dependencies for the whole Reporter object, but for different methods only. This way we are polluting the constructor with dependencies that will be used at only one or two places.

People overly into constructor injection, commonly come up with problems like:

The second version is untestable, as we have no control over the three dependencies. This, in my opinion, is hypocrisy; we’ve all learnt so far that putting in a protected setter just for a unit test is not an evil thing. Having everything tested thoroughly is worth a such a method or two.

“One could call those setters within the package” they argue further… Well, perhaps we should treat each other like professionals who know what they’re doing and not malicious code-monkeys, which try to make the biggest harm possible.

“@Inject, a Spring related dependency is spread in my application”. Well this is not true, as @Inject is in package javax.inject, so this is a javax dependency. Anyway, let’s pretend we have @Autowired instead of @Inject; I’ve never seen a mature application that was ported from Spring to some other IoC container; if you use Spring, you inevitably have it as a dependency. It is, perhaps, not worth the effort to keep Spring-related stuff in the config files only, as it can keep you from reinventing the wheel.

Single responsibility principle is a two ways street. As such, it can be violated two ways: you either create objects with way too many responsibilities, or none. That is, you create your objects so dummy that they have no real logic in them. It’s like someone was like: “Introduce yourself, say that your name is Steven”. Shouldn’t it rather be “Introduce yourself” only, with the responsibility of telling your name left to you? I think it should. Not to mention that in the case of excessive constructor-injection you will -pretty fast- face with monster config files (be it Java or XML) – objects putting together other objects in a long, ugly chain.

In summary, field and constructor injection are two complementary technologies. Using one does not rule out the other; one should, however, apply common sense when dealing with this issue, and should not be overly biased toward one or the another.

Spring injection with Collections

Today I would like to talk about Spring dependency injection when Collections are involved; as Spring treats these data structures in a rather strange way when used as beans.

We, as always, have to distinguish between two cases:

  • constructor and
  • field injection

(the examples below are not meant to represent clever architectural designs. The idea is to prove a point.)

1. Constructor Injection

Let’s suppose we have want to design a file system crawler to detect different types of malicious software signatures. We want to distinguish between different kinds of malicious software, and also want all the infected files to be available to all of our crawlers. Let’s also suppose that we are provided with an interface we cannot modify, and looks like:

public interface Crawler {
    public void crawl();
}

In order to share the list of infected files we are going to use Spring’s constructor injection functionality. First, we create two implementations of the interface above:

public class VirusCrawler implements Crawler {

	private List<String> infectedFiles;

	public VirusCrawler(List<String> infectedFiles) {
		this.infectedFiles = infectedFiles;

	}

	@Override
	public void crawl() {
            //...
	}

and also

public class TrojanCrawler implements Crawler {

	private List<String> infectedFiles;

	public TojanCrawler(List<String> infectedFiles) {
		this.infectedFiles = infectedFiles;

	}

	@Override
	public void crawl() {
            //...
	}
}

Ok now, let’s now put together a configuration for the crawlers; it’s something like:

@Configuration
public class CrawlerConfig {

	@Bean
	public List<String> infectedFiles() {
		return new CopyOnWriteArrayList<String>();
	}

	@Bean
	public Crawler virusCrawler(List<String> infectedFiles) {
		return new VirusCrawler(infectedFiles);
	}

	@Bean
	public Crawler trojanCrawler(List<String> infectedFiles) {
		return new TrojanCrawler(infectedFiles);
	}
}

Surprisingly enough, if you tried to run the code above (provided that you have an extra class that makes Spring start up and read the config above), you would face an exception like:

Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'virusCrawler' defined in class blog.di.CrawlerConfig:
Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.List]: :
No qualifying bean of type [java.lang.String] found for dependency [collection of java.lang.String]:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {};

What now? Spring is trying to inject a list of all beans that are of type String? Cut short: yes it does. Had we had such beans, the code above would have started flawlessly – just try it if you feel like (note that it would have meant broken semantics).

How do we fix this without hacking our business logic? The answer is the miraculous expression language (EL) together with the @Value annotation. Let’s modify our configuration accordingly; we end up with something like this:

@Configuration
public class CrawlerConfig {

	public static final String INFECTED_FILES_LIST = "INFECTED_FILES";

	@Bean(name=INFECTED_FILES_LIST)
	public List<String> infectedFiles() {
		return new CopyOnWriteArrayList<String>();
	}

	@Bean
	public Crawler virusCrawler(@Value("#{" + INFECTED_FILES_LIST + "}")List<String> infectedFiles) {
		return new VirusCrawler(infectedFiles);
	}

	@Bean
	public Crawler trojanCrawler(@Value("#{" + INFECTED_FILES_LIST + "}")List<String> infectedFiles) {
		return new TojanCrawler(infectedFiles);
	}
}

Cool! We’ve just made Spring realize we want our specific List<> injected into our beans.

But wait a minute! This means that if our goal was to inject a list of all our beans which implement the interface Crawler, then we could have achieved that with as few as four lines of code! 

	@Bean
	public CrawlerAggregator aggregator(List<Crawler> crawlers) {
		return new CrawlerAggregator(crawlers);
	}

And I also counted the annotation as a separate line; we didn’t need to inject all the Crawlers one by one and create the list by adding those instances ourselves; we delegated this task to Spring.

2. Field Injection

This one is a bit easier. Let’s suppose we have a bean like this:

public class AwesomeCrawlerBean implements Crawler{
 
    @Autowired
    private List<String> infectedFiles;
 
    public void crawl() {
        //...
        infectedFiles.add(fileName);
        //...
    }
}

No big surprise, the code above throws an exception very similar to the one mentioned above. However,in this case we have two different ways to sort this error out:

  • we either use the expression language as in the previous case
  • or we make use of the @Resource annotation

In the first case, we end up with a class like this – pretty similar to the one described above:

public class AwesomeCrawlerBean implements Crawler{
 
    @Value("#{" + CrawlerConfig.INFECTED_FILES_LIST + "}")
    private List<String> infectedFiles;
 
    public void crawl() {
        //...
        infectedFiles.add(fileName);
        //...
    }
}

While in the second case we just replace the @Autowired annotation with a named @Resource:

public class AwesomeCrawlerBean implements Crawler{
 
    @Resource(name=CrawlerConfig.INFECTED_FILES_LIST)
    private List<String> infectedFiles;
 
    public void crawl() {
        //...
        infectedFiles.add(fileName);
        //...
    }
}

which is perhaps a little bit cleaner and easier to get.

Conclusions

It is not possible to inject Collections with Spring using the traditional ways. Spring will treat collections of type X as a collection of all Spring-managed beans of type X, and not as an empty collection.

In order to clearly state that we want a new, empty Spring-managed collection, we can use either the ExpressionLanguage with the @Value annotation, or (in case of field injection) the @Resource annotation.

Spring’s BeanFactoryAware – DOs and DON’Ts

Spring makes it possible to set application context and/or bean factory into any Spring bean (this is a key point; keep in mind that you cannot inject these object into POJOs). In order to do that, your bean has to implement the interface BeanFactoryAware or ApplicationContextAware. There is only one method you have to implement:

public class OneBean implements BeanFactoryAware {

    private BeanFactory beanFactory;

    //....

    void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

It is now pretty obvious that the class that implements this interface has to be a Spring bean – as the setter method will be called by the container reflectively.

Simply put, it is very easy to get hold of the bean factory object; however, this mechanism should not be overused. Better said, it should be very rarely used. Let’s take some examples when and when should not this thing be used.

Do not inject the bean factory just to publish it to other beans. The injected bean factory should never be published; if you end up writing a getter for it, that should ring the bell:

public class OneBean implements BeanFactoryAware {

    private BeanFactory beanFactory;

    //....

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public BeanFactory getBeanFactory() {
        return beanFactory;
    }
}

This should be avoided, as this anti-pattern does not encourage good dependency injection. In most of the cases dependencies should come through constructor arguments; in more rare cases through method parameters.

Do not inject the bean factory just for getting beans by their name.

public class OneBean implements BeanFactoryAware {

    private BeanFactory beanFactory;

    //....

    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    public void doAwesomeThings() {
        //...
        AwesomeBean awesomeBean = (AwesomeBean)beanFactory.getBean("myAwesomeBean");
        awesomeBean.doSomeWork();
        //...
    }
}

This – again – is not good practice. If you do this, it is not worth doing dependency injection, as the snipped above is not much better than creating objects with the new keyword. Not to mention the hardcoded bean name, which is an anti-pattern in itself, but leave that one for now.

So, when to inject the bean factory? Frankly, I cannot think of very many situations when injecting a bean factory is a good idea. The only acceptable situation that I can think of is when you have a group of similar beans and have to select the one to us after the container has started. Let’s take an example: You have support for several credit cards in your application. The user can select their card type through a user interface. In the business logic, you need the correct credit card handler. You cannot inject this dependency at start up time as you don’t know what to inject; you have to defer this decision until the user has made their selection. Now, you can have something like this:

public class CreditCardProcessorFactory implements BeanFactoryAware {

 private BeanFactory beanFactory;
 private static final String CARD_TYPE_SUFFIX = "CardHandler";
 //....

 public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
 this.beanFactory = beanFactory;
 }

 public CreditCardProcessor getCreditCardProcessor(String cardType) {
 return (CreditCardProcessor)beanFactory.getBean(cardType + CARD_TYPE_SUFFIX);
 }
}

This way you can avoid injecting all the credit card processors you support and use only one of them.

The process is very similar for ApplicationContextAware too. However, it should be even more rare when you need the whole ApplicationContext and not just the BeanFactory.