Spring Autowired annotation

In my previous post I briefly introduced the concept of Spring’s @Autowired annotation. This post goes more in-depth about this annotation, and its importance when developing with the Spring framework.

Spring uses the @Autowired annotation when it determines where it needs to inject a given @Bean. You can see this in the example below:

This example uses @Autowired on a private member variable referenced via class. In this example, the @Component is on the WeatherService class. The DependencyInjectionWithSpring class references the WeatherService class directly. I’ve annotated this reference with the @Autowired annotation. Spring then knows that it needs to find a bean (component) that matches. In this case, it finds the WeatherService class and injects it into the DependencyInjectionWithSpring class.

You can also reference with @Autowired via interface:

Here, I change the WeatherService class to be named WeatherServiceImpl, and have it implement the WeatherService interface, which I’ve also defined. DependencyInjectionWithSpring now references this interface (WeatherService), and the @Autowired annotation stays. Spring then knows that it needs to find a bean/component that implements the WeatherService interface. It finds the WeatherServiceImpl class and injects it into the DependencyInjectionWithSpring as a dependency (weatherService).

Field X in Y required a single bean, but 2 were found

What happens if we have multiple beans (components) that implement the same interface? Like this:

Both SunnyWeatherServiceImpl and CloudyWeatherServiceImpl implement the WeatherService interface. The DependencyInjectionWithSpring class depends on an implementation of WeatherService. Both of these classes would work, since they implement that interface. Spring is aware and manages both of these classes, since they are annotated with the @Component annotation. How does Spring know which one to choose? Let’s run the application and see what happens:

The application is unable to start. Spring can’t determine which bean to set for the weatherService.

How do I fix this?

To resolve this issue and tell Spring which bean to use in this situation, we have a few options.

The first option is to follow the first suggestion given in the exception:

Consider marking one of the beans as @Primary…

The @Primary annotation can be used to indicate to Spring which bean to use. In this case, I add the @Primary annotation to the SunnyWeatherServiceImpl:

Now when I run the application, it starts up with no errors and runs as expected, injecting the SunnyWeatherServiceImpl (the one with the @Primary annotation) into the DependencyInjectionWithSpring class.

There’s another option that Spring gives us, as mentioned in the error message from above:

or using @Qualifier to identify the bean that should be consumed

@Qualifier is a Spring annotation that allows us to tell Spring which bean we want to inject. See below:

Pay particular attention to the DependencyInjectionWithSpring class. The weatherService dependency in this class is now annotated with @Qualifier(value="cloudyWeatherServiceImpl"). This tells Spring to use the cloudyWeatherServiceImpl bean when injecting this dependency.

Now when I run the application, again it starts up with no errors and runs as expected. This time, I told Spring to use the cloudyWeatherServiceImpl class and it prints out The weather is cloudy with a 90% chance of rain as expected.

There’s yet another way to indicate to Spring which bean to inject. This is by naming the variable of the dependency the name of the class we want to inject. Like so:

Here, the WeatherService interface gets the name cloudyWeatherServiceImpl. This tells Spring that I want to inject the bean with the name cloudyWeatherServiceImpl. When I run this code, the application again starts up with no problems, and I again get the expected output.


Spring’s @Autowired annotation is used to indicate where to inject a Spring-managed bean. The @Primary annotation allows us to indicate which bean to use when multiple beans that match are present. The @Qualifier annotation allows us to specify a specific bean to inject on a given dependency. Finally, we learned that we can name the dependency with the bean name to also specify which bean to inject.

Dependency Injection using Spring

This post describes the basics of how to do dependency injection with the Spring framework. If you are unfamiliar with dependency injection, you may want to check out my first post on dependency injection before continuing.

Let’s start of with an example

Here we have two classes – DependencyInjectionWithSpring and WeatherService. WeatherService is a dependency of DependencyInjectionWithSpring. DependencyInjectionWithSpring instantiates WeatherService. Its run() method calls the printWeather() method on WeatherService. Pretty simple stuff.

Can you spot the problem? Take a minute and look at DependencyInjectionWithSpring. This class instantiates the WeatherService class, and sets this object to its private member variable weatherService. This is not a problem per se, or rather not compile time or even a runtime problem. This code still compiles. It still runs. It still produces the result we are trying to achieve.

I don’t see any problems with this, can you explain?

Here are a few

  1. Testability – you can’t test DependencyInjectionWithSpring without testing WeatherService as well. What if weather service gets its data from a thermometer or some external system? You wouldn’t want to wait for the service to run for your tests to complete, that could take a while. Unit tests should run fast. Also, you don’t have control over what WeatherService returns. Since you don’t have this control, how can you test for certain conditions, like returning null or throwing an exception.
  2. Reusability – as in the Testability problem, you can’t reuse DependencyInjectionWithSpring without getting WeatherService. This limits how and where we use this class, since wherever we have DependencyInjectionWithSpring we get WeatherService. What if we wanted different behavior than what WeatherService provides? We can’t in this case.
  3. No configuration without recompilation – what if we wanted to change the implementation of WeatherService? What if, instead of reading the weather from a thermometer we wanted to read it from a web service instead? In our current implementation, we are stuck. We would have to write code to change WeatherService to another implementation, recompile, and redeploy. As mentioned before, if we intend to use DependencyInjectionWithSpring we automatically get the WeatherService implementation with it. In other words, they are highly coupled.

So how does Spring help?

Here’s where the Spring framework can help us out.

The Spring framework is known as an IOC container. An IOC container serves two main purposes:

  1. Manage creation (and full lifecycle) of objects to be used in a system.
  2. Configure coupling of components. Spring provides (or injects) the objects it manages to the classes that depend on these objects.

For #1, that means we can get rid of the new WeatherService() piece. Like this:

If you try to run this, you’ll get a NullPointerException because weatherService has not been instantiated.

How does Spring fix this?

Since Spring is an IOC container it can instantiate objects on our behalf. The objects that get instantiated are known as Beans in the Spring framework. The way that you flag a class that you want Spring to be aware of (that is, you want it to be a Spring bean) is through the @Component annotation, like this:

This annotation lets Spring know that it should create and manage the lifecycle of this object.

However, if we run our code now, we’ll still run into a NullPointerException. Why is this so?

That’s where #2 from above comes into play. The Spring Framework also configures how components are coupled together. It injects objects into the classes that depend on them.


Spring injects objects via the @Autowired annotation. There are multiple ways that @Autowired can be used. To keep things simple, we’ll annotate a private member variable with @Autowired, and let Spring inject it for us. See below:

Pay particular attention to lines 23-24. This is where the WeatherService dependency gets injected into DependencyInjectionWithSpring.

Now, when we run it, we no longer see a NullPointerException, and the text The weather is sunny with a 20% chance of rain gets printed out, as expected.

To reiterate. Spring instantiates the weatherService for us. It also injects it where requested (via the @Autowired annotation).


If you notice in the gist above, and if you run the code, you’ll see that this application is not a web application, but a command line application. In particular, take a look at line 21 above implements CommandLineRunner. CommandLineRunner is an interface from Spring Boot that has one method with the following signature: public void run(String... args) throws Exception. In this example, our DependencyInjectionWithSpring class implements this interface, and in the run method calls the weatherService.printWeather() method.


In this post I described the basics of dependency injection with the Spring framework. Project examples can be found on my Spring Beginner Tutorial on github.

Spring Beginner Tutorial: Dependency Injection Part 3 ā€“ DI without Spring

What is Dependency Injection? ā€“ Part 3

This is the third in a series of blog posts that Iā€™m putting together for developers who are beginning to work with Spring. This post attempts to describe the basics of what dependency injection is.

Dependency injection is a fundamental part of Spring. It is so core to Spring that it warrants some explanation.

In the past couple of posts including this one I haven’t even shown a single line of ‘Spring’ code. Dependency injection, by itself, does not require Spring. In fact, there are many frameworks (outside and within Java) that use Dependency Injection. This is because DI is a design pattern. It’s a way to structure your code and manage your dependencies. It helps you control how classes interact with (and depend on) each other, both in production code as well as and especially in your test code.

Let’s start of with an example. You can follow along on my Spring Beginner Tutorial on github.

In the example below, ‘ExampleRunner’ depends on ‘InterfaceDependency’:

How does interfaceDependency get instantiated and set on ExampleRunner?

The simplest way that it could get instantiated and set is via the constructor of ExampleRunner. We could ‘new’ it up in the constructor of ExampleRunner, like so:

But this creates a problem. ExampleRunner is now coupled to a concrete implementation, InterfaceDependencyImpl, which is a concrete class (i.e. not an interface). This is a problem because every place ExampleRunner is used, it is always going to use InterfaceDependencyImpl. They are coupled together, inseparable, and there’s nothing a client of ExampleRunner can do about that.

Testing concerns

One place where coupling becomes a problem is when we want to unit test ExampleRunner. What if, for example, InterfaceDependencyImpl made a network call, or talked to a database, or performed some other long running operation. Now, anytime we run our unit tests against ExampleRunner we must wait for the network call to return (long and brittle), or depend on a database server to be running (unneeded dependency), or wait for some other process to finish. This is not good.

Dependency Injection to the rescue!

We can solve this problem with Dependency Injection (DI for short). DI follows the dependency inversion principle, which states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend on details. Details should depend on abstractions.

In our example above, ExampleRunner needs remove its dependency on InterfaceDependencyImpl. But how to we do that?

We do that by introducing the idea of an Injector.

An Injector is an object that coordinates dependencies. To keep things simple, the Injector in this example is the main method. Its job is to instantiate and set, or ‘inject’ dependencies.

Types of Injection

There are two different ways that dependencies are injected: Constructor Injection and Setter Injection.

Constructor Injection

The first method of injecting dependencies that I’ll describe is Constructor Injection. Take a look at the example below. This is code that exists in the Injector (main method in this example):

Here, we instantiate InterfaceDependencyImpl. We then pass it in as a constructor argument to ExampleRunner. The passing in as an argument to the constructor is the ‘injection’ part. This is Constructor Injection since the point we are injecting it into is the constructor.

If you run this code, you’ll see the following printed out:

Setter Injection

Setter injection is done via a method, typically a setter method. In the example below, InterfaceDependencyImpl is passed into ExampleRunner via the setDependency method. You may have noticed that I don’t pass in any arguments to the constructor in this example — the dependency gets set via the setter:

Constructor injection and Setter injection are the most common ways to inject dependencies. I personally prefer constructor injection for all dependencies, as I prefer to have all my dependencies in place before a class is used. For me, I like knowing that the class has everything it needs before it’s used. However, there are cases where setter injection is appropriate. For example, sometimes you can avoid circular dependencies if you set the problematic property via setter injection (though you should avoid circular dependencies where possible anyway). In my current project, I can’t think of a single place where we use setter injection, and it’s a good-sized project.

What were you saying about testing?

Back to the testing discussion. If you remember, I stated that when two classes are too tightly coupled, testing becomes more difficult (and sometimes impossible). Being able to specify the dependencies of a class helps in this regard. For example, if I am writing tests for ExampleRunner, and I need to simulate specific behavior of InterfaceDependencyImpl (for example, throw an exception), it becomes problematic if ExampleRunner itself instantiates InterfaceDependencyImpl. It’s a problem because ExampleRunner nor my unit test can control whether InterfaceDependencyImpl throws an exception or not. There’s no reliable way to simulate that. If ExampleRunner controls the instantiation and setting of this dependency, I have no choice but to test with that implementation. However, if I use DI to set my dependencies, I do have control of the dependencies of the class I’m testing. So, if I wanted to simulate an exception, I can create a test class InterfaceDependencyWithExceptionImpl, which throws an exception when invoked. I then inject this implementation for the interfaceDependency property (via either Setter or Constructor injection, it doesn’t matter). My test code can then focus on the behavior of the unit under test (ExampleRunner in this case), and how it reacts to scenarios like a dependency throwing an exception. This way I can set up my tests in a way that simulates a wider variety of scenarios.


Dependency Injection is fundamental to understand when learning Spring. Furthermore, it promotes good design by encouraging components to be loosely coupled. DI promotes separating the creation of a class’s dependencies from the behavior of those classes, and opens up numerous testing scenarios. In these examples I purposely left Spring out, as my intention here is to show you simple examples of Dependency Injection so that you’re not bogged down with syntax and Spring-specific details.

Spring Beginner Tutorial: Dependency Injection Part 2 ā€“ What is a Dependency?

What is Dependency Injection? — Part 2

This is the second in a series of blog posts that I’m putting together for developers who are beginning to work with Spring. This post attempts to describe the fundamentals of what a dependency is.

In order to understand Dependency Injection (sometimes people call it Inversion of Control), we need to understand what dependencies are. Take a look at the Java code below. You can find the full example at my Spring Beginner Tutorial github repo.

I’ve tried to give the simplest example I could think of. In this example we have three classes, ExampleRunner, ClassDependency, and InterfaceDependency. We’ll get into the differences below. ExampleRunner depends on both ClassDependency and InterfaceDependency. In the run method of the ExampleRunner class above, we instantiate both ClassDependency and InterfaceDependency, and then call methods on both of these classes.

What does it mean when we say one class depends on another class?

The reason is simple. We say that one class depends on another because one class needs to call methods (or get information from, etc) on the class it depends on. In order for it to complete its job, it needs or depends on the other class. Without that class, it can’t carry out the work that it expects to do.

What is coupling?

Often, you’ll hear the term ‘coupling’ used in discussions of class dependencies. When one class uses another, we say that they are ‘coupled’. In other words, where you have dependencies, you have coupling, at least in a very basic form.

Types of Dependencies

Since I’ve now covered the basics, let’s dive into the different types of dependencies.

  • Class dependencies
  • Interface dependencies
  • Method dependencies
  • Field dependencies
  • Dependency in method

Class dependencies

Class dependencies are when one class depends on another class. In the example above, ExampleRunner depends on ClassDependency. ClassDependency is a concrete type — i.e. it’s not an interface.

Interface dependencies

ExampleRunner also depends on InterfaceDependency, which, as its name implies, is an interface dependency. InterfaceDependency is an interface. In this example, there is a somewhat hidden dependency in that since we instantiate InterfaceDependencyImpl, ExampleRunner also depends on this class. Later in the tutorial, we’ll get into how Spring helps us remove that dependency, but for now the thing to focus on is that InterfaceDependency is an interface, and the ExampleRunner class calls methods on it through this interface.

Field dependencies

In the example above, ExampleRunner also depends on a field. In this case it’s a field called ‘getField()’ (great name, I know :)). This is called a field dependency in that one class (ExampleRunner in our case) depends on the field of another (getField() on the ClassDependency class). This is what we’ll call a ‘field dependency’.

Dependency in method

Take a look at the dependencyInMethod method. Here, we again depend on ClassDependency. It’s just that, this time, the dependency is contained in a method, not as a field to the ExampleRunner class.

Import statements

One way to get a feel for the interface or class dependencies a given class has is to look at its import statements. Here you can find the packages or classes that contain the classes that the class you are examining uses. There’s a drawback to this, however, in that you won’t be able to see at a glance which classes the given class uses if those classes exist in the same package (since you don’t need to import classes that exist in the same package as the current class).


In this tutorial I describe what a dependency is, and give examples of the different types of dependencies. Understanding this is fundamental for understanding DependencyInjection and Spring.

Spring Beginner Tutorial: Dependency Injection Part 1 – ExampleRunner

What is Dependency Injection? – Part 1

This is the first in a series of blog posts that I’m putting together for developers who are beginning to work with Spring. This post sets us up to understand a basic principle of Spring – Dependency Injection.

To start us off, I’ve created a simple class with a main method. As you can see in the snippet below, all the main method does is instantiate an ExampleRunner class and call the run() method on it. This is what we’ll use to kick off the examples that follow.

Find the snippet below. You can see the full version of this example at my Spring Beginner Tutorial github repo:

In my next post we’ll dig into the fundamentals of Dependency Injection. Sometimes people call it Inversion of Control.


This is the introductory blog post that sets us up for the rest of the tutorial. It describes a simple class that allows us to execute code where we can view the examples that follow.

I hope you’ll follow along and find the tutorial helpful. I’ve been doing Spring for several years now, and I’ve felt that a simple tutorial for beginners is more than overdue. As always, send me your feedback and comments.