0% found this document useful (0 votes)
404 views

Baeldung 1

The document discusses the differences between the @Component, @Repository, and @Service annotations in Spring. It explains that @Component is a generic stereotype for any Spring-managed component, @Service annotates classes at the service layer, and @Repository annotates classes at the persistence layer. The major difference between these stereotypes is that they are used for different classifications - @Component can be used across the application, @Repository is for catching persistence exceptions, and @Service marks classes in the service layer. The document also provides examples of how to inject values using the @Value annotation in Spring.

Uploaded by

Fake Email
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
404 views

Baeldung 1

The document discusses the differences between the @Component, @Repository, and @Service annotations in Spring. It explains that @Component is a generic stereotype for any Spring-managed component, @Service annotates classes at the service layer, and @Repository annotates classes at the persistence layer. The major difference between these stereotypes is that they are used for different classifications - @Component can be used across the application, @Repository is for catching persistence exceptions, and @Service marks classes in the service layer. The document also provides examples of how to inject values using the @Value annotation in Spring.

Uploaded by

Fake Email
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

9/16/2019 @Component vs @Repository and @Service in Spring | Baeldung

Read more (https://www.baeldung.com/spring-quali er-annotation) →

2. Spring Annotations

In most typical applications, we have distinct layers like data access, presentation, service, business, etc.
And, in each layer, we have various beans. Simply put, to detect them automatically,  Spring uses classpath
scanning annotations.
Then, it registers each bean in the ApplicationContext.
Here's a quick overview of a few of these annotations:
@Component is a generic stereotype for any Spring-managed component
@Service annotates classes at the service layer
@Repository annotates classes at the persistence layer, which will act as a database repository
We already have an extended article (https://www.baeldung.com/spring-bean-annotations) about these
annotations. So we'll keep the focus only on the di erences between them.

3. What's Di erent?

The major di erence between these stereotypes is they are used for di erent classi cation. When we
annotate a class for auto-detection, then we should use the respective stereotype.
Now, let's go through them in more detail.

3.1. @Component

We can use @Component across the application to mark the beans as Spring's managed components.
Spring only pick up and registers beans with @Component  and doesn't look for @Service and @Repository
in general.
They are registered in ApplicationContext because they themselves are annotated with @Component:

1 @Component
2 public @interface Service {
3 }

1 @Component
2 public @interface Repository {
3 }

@Service and @Repository are special cases of @Component. They are technically the same but we use
them for the di erent purposes.

3.2. @Repository

@Repository’s job is to catch persistence speci c exceptions and rethrow them as one of Spring’s
uni ed unchecked exception.
For this Spring provides PersistenceExceptionTranslationPostProcessor, that requires to add in our
application context:

https://www.baeldung.com/spring-component-repository-service 2/4
9/16/2019 @Component vs @Repository and @Service in Spring | Baeldung
1 <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

This bean post processor adds an advisor to any bean that’s annotated with @Repository.

3.3. @Service

We mark beans with @Service to indicate that it's holding the business logic. So there's no any other
specialty except using it in the service layer.

4. Conclusion

In this write-up, we learned about the di erences between  @Component, @Repository,


@Service annotations. We examined each annotation separately with the areas of their use.
As a conclusion, it's always a good idea to choose the annotation-based on their layer conventions.
 

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Learning to build your API


with Spring?

https://www.baeldung.com/spring-component-repository-service 3/4
9/16/2019 A Quick Guide to Spring @Value | Baeldung

(/)

A Quick Guide to Spring @Value


Last modi ed: September 4, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Annotations (https://www.baeldung.com/tag/spring-annotations/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this quick article, we're going to have a look at the @Value Spring annotation.
This annotation can be used for injecting values into elds in Spring-managed beans and it can be applied
at the eld or constructor/method parameter level.

Further reading:
What is a Spring Bean? (https://www.baeldung.com/spring-bean)
A quick and practical explanation of what a Spring Bean is.

Read more (https://www.baeldung.com/spring-bean) →

Using Spring @Value with Defaults (https://www.baeldung.com/spring-


value-defaults)
A quick and practical guide to setting default values when using the @Value annotation in Spring.

Read more (https://www.baeldung.com/spring-value-defaults) →

https://www.baeldung.com/spring-value-annotation 1/5
9/16/2019 A Quick Guide to Spring @Value | Baeldung

2. Setting up the Application

To describe di erent kinds of usage for this annotation, we need to con gure a simple Spring application
con guration class.
And naturally, we'll need a properties le to de ne the values we want to inject with the @Value
annotation. And so, we'll rst need to de ne a @PropertySource in our con guration class – with the
properties le name.
Let's de ne the properties le:

1 value.from.file=Value got from the file


2 priority=Properties file
3 listOfValues=A,B,C

3. Usage Examples

As a basic and mostly useless usage example we can only inject “string value” from the annotation to the
eld:

1 @Value("string value")
2 private String stringValue;

Using the @PropertySource annotation allows us to work with values from properties les with the @Value
annotation. In the following example we get “Value got from the le” assigned to the eld:

1 @Value("${value.from.file}")
2 private String valueFromFile;

We can also set the value from system properties with the same syntax. Let's assume that we have de ned
a system property named systemValue and look at the following sample:

1 @Value("${systemValue}")
2 private String systemValue;

Default values can be provided for properties that might not be de ned. In this example the value “some
default” will be injected:

1 @Value("${unknown.param:some default}")
2 private String someDefault;

If the same property is de ned as a system property and in the properties le, then the system property
would be applied.
Suppose we had a property priority de ned as a system property with the value “System property” and
de ned as something else in the properties le. In the following code the value would be “System
property”:

1 @Value("${priority}")
2 private String prioritySystemProperty;

Sometimes we need to inject a bunch of values. It would be convenient to de ne them as comma-


separated values for the single property in the properties le or as a system property and to inject into an
array. In the rst section, we de ned comma-separated values in the listOfValues of the properties le, so in
the following example the array values would be [“A”, “B”, “C”]:

https://www.baeldung.com/spring-value-annotation 2/5
9/16/2019 A Quick Guide to Spring @Value | Baeldung
1 @Value("${listOfValues}")
2 private String[] valuesArray;

4. Advanced Examples with SpEL

We can also use SpEL expressions to get the value. If we have a system property named priority, then its
value will be applied to the eld in the next example:

1 @Value("#{systemProperties['priority']}")
2 private String spelValue;

If we have not de ned the system property, then the null value will be assigned. To prevent this, we can
provide a default value in the SpEL expression. In the following example, we get “some default” value for
the eld if the system property is not de ned:

1 @Value("#{systemProperties['unknown'] ?: 'some default'}")


2 private String spelSomeDefault;

Furthermore, we can use a eld value from other beans. Suppose we have a bean named someBean with a
eld someValue equal to 10. Then 10 will be assigned to the eld in this example:

1 @Value("#{someBean.someValue}")
2 private Integer someBeanValue;

We can manipulate properties to get a List of values. In the following sample, we get a list of string values
A, B, and C:

1 @Value("#{'${listOfValues}'.split(',')}")
2 private List<String> valuesList;

5. Using @Value with Maps

We can also use the @Value annotation to inject a Map property.


First, we'll need to de ne the property in the {key: ‘value' } form in our properties le:

1 valuesMap={key1: '1', key2: '2', key3: '3'}

Note that the values in the Map must be in single quotes.


Now we can inject this value from the property le as a Map:

1 @Value("#{${valuesMap}}")
2 private Map<String, Integer> valuesMap;

If we need to get the value of a speci c key in the Map, all we have to do is add the key's name in the
expression:

https://www.baeldung.com/spring-value-annotation 3/5
9/16/2019 A Quick Guide to Spring @Value | Baeldung
1 @Value("#{${valuesMap}.key1}")
2 private Integer valuesMapKey1;

If we're not sure whether the Map contains a certain key, we should choose a safer expression that will not
throw an exception but set the value to null when the key is not found:

1 @Value("#{${valuesMap}['unknownKey']}")
2 private Integer unknownMapKey;

We can also set default values for the properties or keys that might not exist:

1 @Value("#{${unknownMap : {key1: '1', key2: '2'}}}")


2 private Map<String, Integer> unknownMap;
3  
4 @Value("#{${valuesMap}['unknownKey'] ?: 5}")
5 private Integer unknownMapKeyWithDefaultValue;

Map entries can also be ltered before injection. Let's assume we need to get only those entries whose
values are greater than one:

1 @Value("#{${valuesMap}.?[value>'1']}")
2 private Map<String, Integer> valuesMapFiltered;

We can also use the @Value annotation to inject all current system properties:

1 @Value("#{systemProperties}")
2 private Map<String, String> systemPropertiesMap;

6. Conclusion

In this quick tutorial, we examined the various possibilities of using the @Value annotation with simple
properties de ned in the le, with system properties, and with properties calculated with SpEL expressions.
As always the example application is available on GitHub project
(https://github.com/eugenp/tutorials/tree/master/spring-boot-properties).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

 newest  oldest  most voted

https://www.baeldung.com/spring-value-annotation 4/5
9/16/2019 Constructor Dependency Injection in Spring | Baeldung

(/)

Constructor Dependency Injection in


Spring
Last modi ed: July 29, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Introduction

Arguably one of the most important development principles of modern software design is Dependency
Injection (DI) which quite naturally ows out of another critically important principle: Modularity.
This article will explore a speci c type of DI technique called Constructor-Based Dependency Injection
within Spring – which simply put, means that required components are passed into a class at the time of
instantiation.

To get started we need to import spring-context dependency in our pom.xml:

1 <dependency>
2     <groupId>org.springframework</groupId>
3     <artifactId>spring-context</artifactId>
4     <version>5.1.4.RELEASE</version>
5 </dependency>

Then we need to set up a Con guration le. This le can be either a POJO or if you prefer, an XML le.

Further reading:

https://www.baeldung.com/constructor-injection-in-spring 1/5
9/16/2019 Constructor Dependency Injection in Spring | Baeldung

Intro to Inversion of Control and Dependency Injection with Spring


(https://www.baeldung.com/inversion-control-and-dependency-injection-
in-spring)
A quick introduction to the concepts of Inversion of Control and Dependency Injection, followed by a simple
demonstration using the Spring Framework

Read more (https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring) →

Top Spring Framework Interview Questions


(https://www.baeldung.com/spring-interview-questions)
A quick discussion of common questions about the Spring Framework that might come up during a job
interview.

Read more (https://www.baeldung.com/spring-interview-questions) →

Wiring in Spring: @Autowired, @Resource and @Inject


(https://www.baeldung.com/spring-annotations-resource-inject-autowire)
This article will compare and contrast the use of annotations related to dependency injection, namely the
@Resource, @Inject, and @Autowired annotations.

Read more (https://www.baeldung.com/spring-annotations-resource-inject-autowire) →

2. Annotation Based Con guration

Java con guration le looks pretty much like a plain-old Java object with some additional annotations:

1 @Configuration
2 @ComponentScan("com.baeldung.constructordi")
3 public class Config {
4  
5     @Bean
6     public Engine engine() {
7         return new Engine("v8", 5);
8     }
9  
10     @Bean
11     public Transmission transmission() {
12         return new Transmission("sliding");
13     }
14 }

Here we are using annotations to notify Spring runtime that this class is a provider of bean de nitions
(@Bean annotation) and that a context scan for additional beans needs to be performed in package
com.baeldung.spring. Next, we de ne a Car class:

1 @Component
2 public class Car {
3  
4     @Autowired
5     public Car(Engine engine, Transmission transmission) {
6         this.engine = engine;
7         this.transmission = transmission;
8     }
9 }

Spring will encounter our Car class while doing a package scan and will initialize its instance by calling the
@Autowired annotated constructor.
Instances of Engine and Transmission will be obtained by calling @Bean annotated methods of the Con g
class. Finally, we need to bootstrap an ApplicationContext using our POJO con guration:
https://www.baeldung.com/constructor-injection-in-spring 2/5
9/16/2019 Constructor Dependency Injection in Spring | Baeldung
1 ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
2 Car car = context.getBean(Car.class);

3. Implicit Constructor Injection

As of Spring 4.3, classes with a single constructor can omit the @Autowired annotation. A nice little bit of
convenience and boilerplate removal!
On top of that, also starting with 4.3, constructor-based injection can be leveraged in @Con guration
annotated classes. And yes, if such a class has only one constructor the @Autowired annotation can be
omitted as well.

4. XML Based Con guration

Another way to con gure Spring runtime with constructor-based dependency injection is to use an xml
con guration le:

1 <bean id="toyota" class="com.baeldung.constructordi.domain.Car">


2     <constructor-arg index="0" ref="engine"/>
3     <constructor-arg index="1" ref="transmission"/>
4 </bean>
5  
6 <bean id="engine" class="com.baeldung.constructordi.domain.Engine">
7     <constructor-arg index="0" value="v4"/>
8     <constructor-arg index="1" value="2"/>
9 </bean>
10  
11 <bean id="transmission" class="com.baeldung.constructordi.domain.Transmission">
12     <constructor-arg value="sliding"/>
13 </bean>

Note that constructor-arg can accept a literal value or a reference to another bean and that an optional
explicit index and type can be provided. Type and index attributes can be used to resolve ambiguity (for
example if a constructor takes multiple arguments of the same type).

name attribute could also be used for xml to java variable matching, but then your
code must be compiled with debug ag on.

A Spring application context, in this case, needs to be bootstrapped using ClassPathXmlApplicationContext:

1 ApplicationContext context = new ClassPathXmlApplicationContext("baeldung.xml");


2 Car car = context.getBean(Car.class);

5. Conclusion

This quick tutorial has showcased the basics of two distinct ways to use Constructor-Based Dependency
Injection using Spring framework.

The full implementation of this tutorial can be found over on Github


(https://github.com/eugenp/tutorials/tree/master/spring-core).

https://www.baeldung.com/constructor-injection-in-spring 3/5
9/16/2019 Guide to Spring @Autowired | Baeldung

(/)

Guide to Spring @Autowired


Last modi ed: September 4, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

Starting with Spring 2.5, the framework introduced a new style of Dependency Injection driven by
@Autowired Annotations. This annotation allows Spring to resolve and inject collaborating beans into your
bean.
In this tutorial, we will look at how to enable autowiring, various ways to wire in beans, making beans
optional, resolving bean con icts using @Quali er annotation along with potential exception scenarios.

Further reading:
Spring Component Scanning (https://www.baeldung.com/spring-
component-scanning)
Learn about the mechanism behind Spring component scanning, and how you can tweak it to your own needs

Read more (https://www.baeldung.com/spring-component-scanning) →

Intro to Inversion of Control and Dependency Injection with Spring


(https://www.baeldung.com/inversion-control-and-dependency-injection-
in-spring)

https://www.baeldung.com/spring-autowire 1/7
9/16/2019 Guide to Spring @Autowired | Baeldung
A quick introduction to the concepts of Inversion of Control and Dependency Injection, followed by a simple
demonstration using the Spring Framework

Read more (https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring) →

2. Enabling @Autowired Annotations

If you are using Java based con guration in your application you can enable annotation-driven injection by
using AnnotationCon gApplicationContext to load your spring con guration as below:

1 @Configuration
2 @ComponentScan("com.baeldung.autowire.sample")
3 public class AppConfig {}

As an alternative, in Spring XML, it can be enabled by declaring it in Spring XML les like so:
<context:annotation-con g/>

3. Using @Autowired

Once annotation injection is enabled, autowiring can be used on properties, setters, and constructors.

3.1. @Autowired on Properties

The annotation can be used directly on properties, therefore eliminating the need for getters and setters:

1 @Component("fooFormatter")
2 public class FooFormatter {
3  
4     public String format() {
5         return "foo";
6     }
7 }

1 @Component
2 public class FooService {
3      
4     @Autowired
5     private FooFormatter fooFormatter;
6  
7 }

In the above example, Spring looks for and injects fooFormatter when FooService is created.

3.2. @Autowired on Setters

The @Autowired annotation can be used on setter methods. In the below example, when the annotation is
used on the setter method, the setter method is called with the instance of FooFormatter when FooService
is created:

https://www.baeldung.com/spring-autowire 2/7
9/16/2019 Guide to Spring @Autowired | Baeldung
1 public class FooService {
2  
3     private FooFormatter fooFormatter;
4  
5     @Autowired
6     public void setFooFormatter(FooFormatter fooFormatter) {
7             this.fooFormatter = fooFormatter;
8     }
9 }

3.3. @Autowired on Constructors

The @Autowired annotation can also be used on constructors. In the below example, when the annotation
is used on a constructor, an instance of FooFormatter is injected as an argument to the constructor when
FooService is created:

1 public class FooService {


2  
3     private FooFormatter fooFormatter;
4  
5     @Autowired
6     public FooService(FooFormatter fooFormatter) {
7         this.fooFormatter = fooFormatter;
8     }
9 }

4. @Autowired and Optional Dependencies

Spring expects @Autowired dependencies to be available when the dependent bean is being constructed.
If the framework cannot resolve a bean for wiring, it will throw the below-quoted exception and prevent the
Spring container from launching successfully:

1 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:


2 No qualifying bean of type [com.autowire.sample.FooDAO] found for dependency:
3 expected at least 1 bean which qualifies as autowire candidate for this dependency.
4 Dependency annotations:
5 {@org.springframework.beans.factory.annotation.Autowired(required=true)}

To avoid this from happening, a bean can optional be speci ed as below:

1 public class FooService {


2  
3     @Autowired(required = false)
4     private FooDAO dataAccessor;
5      
6 }

5. Autowire Disambiguation

By default, Spring resolves @Autowired entries by type. If more than one beans of the same type are
available in the container, the framework will throw a fatal exception indicating that more than one bean is
available for autowiring.

5.1. Autowiring by @Quali er

The @Quali er annotation can be used to hint at and narrow down the required bean:

https://www.baeldung.com/spring-autowire 3/7
9/16/2019 Guide to Spring @Autowired | Baeldung
1 @Component("fooFormatter")
2 public class FooFormatter implements Formatter {
3  
4     public String format() {
5         return "foo";
6     }
7 }

1 @Component("barFormatter")
2 public class BarFormatter implements Formatter {
3  
4     public String format() {
5         return "bar";
6     }
7 }

1 public class FooService {


2      
3     @Autowired
4     private Formatter formatter;
5  
6 }

Since there are two concrete implementations of Formatter available for the Spring container to inject,
Spring will throw a NoUniqueBeanDe nitionException exception when constructing the FooService:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException:


No qualifying bean of type [com.autowire.sample.Formatter] is defined:
expected single matching bean but found 2: barFormatter,fooFormatter

This can be avoided by narrowing the implementation using a @Quali er annotation:

1 public class FooService {


2      
3     @Autowired
4     @Qualifier("fooFormatter")
5     private Formatter formatter;
6  
7 }

By specifying the @Quali er with the name of the speci c implementation, in this case as fooFormatter, we
can avoid ambiguity when Spring nds multiple beans of the same type.
Please note that the value of the @Quali er annotation matches with the name declared in the
@Component annotation of our FooFormatter implementation.

5.2. Autowiring by Custom Quali er


https://www.baeldung.com/spring-autowire 4/7
9/16/2019 Guide to Spring @Autowired | Baeldung

Spring allows us to create our own @Quali er annotation. To create a custom Quali er, de ne an annotation
and provide the @Quali er annotation within the de nition as below:

1 @Qualifier
2 @Target({
3   ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
4 @Retention(RetentionPolicy.RUNTIME)
5 public @interface FormatterType {
6      
7     String value();
8  
9 }

Once de ned, the FormatterType can be used within various implementations to specify custom value:

1 @FormatterType("Foo")
2 @Component
3 public class FooFormatter implements Formatter {
4  
5     public String format() {
6         return "foo";
7     }
8 }

1 @FormatterType("Bar")
2 @Component
3 public class BarFormatter implements Formatter {
4  
5     public String format() {
6         return "bar";
7     }
8 }

Once the implementations are annotated, the custom Quali er annotation can be used as below:

1 @Component
2 public class FooService {
3      
4     @Autowired
5     @FormatterType("Foo")
6     private Formatter formatter;
7      
8 }

The value speci ed in the @Target annotation restrict where the quali er can be used to mark injection
points.
In the above code snippet, the quali er can be used to disambiguate the point where Spring can inject the
bean into a eld, a method, a type, and a parameter.

5.3. Autowiring by Name

As a fallback Spring uses the bean name as a default quali er value.


So by de ning the bean property name, in this case as fooFormatter, Spring matches that to the
FooFormatter implementation and injects that speci c implementation when FooService is constructed:

1 public class FooService {


2      
3     @Autowired
4     private Formatter fooFormatter;
5      
6 }

6. Conclusion
https://www.baeldung.com/spring-autowire 5/7
9/16/2019 Guide to Spring @Autowired | Baeldung

Although both @Quali er and bean name fallback match can be used to narrow down to a speci c bean,
autowiring is really all about injection by type and this is how best to use this container feature.
The source code of this tutorial can be found in the GitHub project
(https://github.com/eugenp/tutorials/tree/master/spring-all) – this is an Eclipse based project, so it
should be easy to import and run as it is.

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Comments are closed on this article!

(https://www.ezoic.com/what-is-ezoic/) report this

CATEGORIES

SPRING (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTPS://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JSON/JACKSON/)
HTTP CLIENT-SIDE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/HTTP/)
KOTLIN (HTTPS://WWW.BAELDUNG.COM/CATEGORY/KOTLIN/)

SERIES

JAVA “BACK TO BASICS” TUTORIAL (/JAVA-TUTORIAL)


JACKSON JSON TUTORIAL (/JACKSON)
HTTPCLIENT 4 TUTORIAL (/HTTPCLIENT-GUIDE)

https://www.baeldung.com/spring-autowire 6/7
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

(/)

Intro to Inversion of Control and


Dependency Injection with Spring
Last modi ed: September 12, 2019

by Loredana Crusoveanu (https://www.baeldung.com/author/loredana-crusoveanu/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this article, we'll introduce the concepts of IoC (Inversion of Control) and DI (Dependency Injection), and
we'll then take a look at how these are implemented in the Spring framework.

Further reading:
Wiring in Spring: @Autowired, @Resource and @Inject
(https://www.baeldung.com/spring-annotations-resource-inject-autowire)
This article will compare and contrast the use of annotations related to dependency injection, namely the
@Resource, @Inject, and @Autowired annotations.

Read more (https://www.baeldung.com/spring-annotations-resource-inject-autowire) →

@Component vs @Repository and @Service in Spring


(https://www.baeldung.com/spring-component-repository-service)
Learn about the di erences between the @Component, @Repository and @Service annotations and when to
use them.

Read more (https://www.baeldung.com/spring-component-repository-service) →

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 1/8
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

2. What Is Inversion of Control?

Inversion of Control is a principle in software engineering by which the control of objects or portions of a
program is transferred to a container or framework. It's most often used in the context of object-oriented
programming.

By contrast with traditional programming, in which our custom code makes calls to a library, IoC enables a
framework to take control of the ow of a program and make calls to our custom code. To enable this,
frameworks use abstractions with additional behavior built in. If we want to add our own behavior, we
need to extend the classes of the framework or plugin our own classes.
The advantages of this architecture are:
decoupling the execution of a task from its implementation
making it easier to switch between di erent implementations
greater modularity of a program
greater ease in testing a program by isolating a component or mocking its dependencies and allowing
components to communicate through contracts
Inversion of Control can be achieved through various mechanisms such as: Strategy design pattern, Service
Locator pattern, Factory pattern, and Dependency Injection (DI).
We're going to look at DI next.

3. What is Dependency Injection?

Dependency injection is a pattern through which to implement IoC, where the control being inverted is the
setting of object's dependencies.
The act of connecting objects with other objects, or “injecting” objects into other objects, is done by an
assembler rather than by the objects themselves.
Here's how you would create an object dependency in traditional programming:

1 public class Store {


2     private Item item;
3   
4     public Store() {
5         item = new ItemImpl1();   
6     }
7 }

In the example above, we need to instantiate an implementation of the Item interface within the Store class
itself.
By using DI, we can rewrite the example without specifying the implementation of Item that we want:

1 public class Store {


2     private Item item;
3     public Store(Item item) {
4         this.item = item;
5     }
6 }

In the next sections, we'll see how we can provide the implementation of Item through metadata.
Both IoC and DI are simple concepts, but have deep implications in the way we structure our systems, so
they're well worth understanding well.

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 2/8
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

4. The Spring IoC Container

An IoC container is a common characteristic of frameworks that implement IoC.

In the Spring framework, the IoC container is represented by the interface ApplicationContext. The Spring
container is responsible for instantiating, con guring and assembling objects known as beans, as well as
managing their lifecycle.
The Spring framework provides several implementations of the ApplicationContext interface —
ClassPathXmlApplicationContext and FileSystemXmlApplicationContext for standalone applications, and
WebApplicationContext for web applications.
In order to assemble beans, the container uses con guration metadata, which can be in the form of XML
con guration or annotations.
Here's one way to manually instantiate a container:

1 ApplicationContext context
2   = new ClassPathXmlApplicationContext("applicationContext.xml");

To set the item attribute in the example above, we can use metadata. Then, the container will read this
metadata and use it to assemble beans at runtime.
Dependency Injection in Spring can be done through constructors, setters or elds.

5. Constructor-Based Dependency Injection

In the case of constructor-based dependency injection (/constructor-injection-in-spring), the container will


invoke a constructor with arguments each representing a dependency we want to set.
Spring resolves each argument primarily by type, followed by name of the attribute and index for
disambiguation. Let's see the con guration of a bean and its dependencies using annotations:

1 @Configuration
2 public class AppConfig {
3  
4     @Bean
5     public Item item1() {
6         return new ItemImpl1();
7     }
8  
9     @Bean
10     public Store store() {
11         return new Store(item1());
12     }
13 }

The @Con guration annotation indicates that the class is a source of bean de nitions. Also, we can add it to
multiple con guration classes.
The @Bean annotation is used on a method to de ne a bean. If we don't specify a custom name, the bean
name will default to the method name.

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 3/8
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

For a bean with the default singleton scope, Spring rst checks if a cached instance of the bean already
exists and only creates a new one if it doesn't. If we're using the prototype scope, the container returns a
new bean instance for each method call.
Another way to create the con guration of the beans is through XML con guration:

1 <bean id="item1" class="org.baeldung.store.ItemImpl1" />


2 <bean id="store" class="org.baeldung.store.Store">
3     <constructor-arg type="ItemImpl1" index="0" name="item" ref="item1" />
4 </bean>

6. Setter-Based Dependency Injection

For setter-based DI, the container will call setter methods of our class, after invoking a no-argument
constructor or no-argument static factory method to instantiate the bean. Let's create this con guration
using annotations:

1 @Bean
2 public Store store() {
3     Store store = new Store();
4     store.setItem(item1());
5     return store;
6 }

We can also use XML for the same con guration of beans:

1 <bean id="store" class="org.baeldung.store.Store">


2     <property name="item" ref="item1" />
3 </bean>

Constructor-based and setter-based types of injection can be combined for the same bean. The Spring
documentation recommends using constructor-based injection for mandatory dependencies, and setter-
based injection for optional ones.

7. Field-Based Dependency Injection

In case of Field-Based DI, we can inject the dependencies by marking them with an @Autowired
annotation:

1 public class Store {


2     @Autowired
3     private Item item;
4 }

While constructing the Store object, if there's no constructor or setter method to inject the Item bean, the
container will use re ection to inject Item into Store.
We can also achieve this using XML con guration (/spring-xml-injection).

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 4/8
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

This approach might look simpler and cleaner but is not recommended to use because it has a few
drawbacks such as:
This method uses re ection to inject the dependencies, which is costlier than constructor-based or
setter-based injection
It's really easy to keep adding multiple dependencies using this approach. If you were using
constructor injection having multiple arguments would have made us think that the class does more
than one thing which can violate the Single Responsibility Principle.
More information on @Autowired annotation can be found in Wiring In Spring (/spring-annotations-
resource-inject-autowire) article.

8. Autowiring Dependencies

Wiring (/spring-annotations-resource-inject-autowire) allows the Spring container to automatically resolve


dependencies between collaborating beans by inspecting the beans that have been de ned.
There are four modes of autowiring a bean using an XML con guration:
no: the default value – this means no autowiring is used for the bean and we have to explicitly name
the dependencies
byName: autowiring is done based on the name of the property, therefore Spring will look for a bean
with the same name as the property that needs to be set
byType: similar to the byName autowiring, only based on the type of the property. This means Spring
will look for a bean with the same type of the property to set. If there's more than one bean of that
type, the framework throws an exception.
constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans
with the same type as the constructor arguments
For example, let's autowire the item1 bean de ned above by type into the store bean:

1 @Bean(autowire = Autowire.BY_TYPE)
2 public class Store {
3      
4     private Item item;
5  
6     public setItem(Item item){
7         this.item = item;   
8     }
9 }

We can also inject beans using the @Autowired annotation for autowiring by type:

1 public class Store {


2      
3     @Autowired
4     private Item item;
5 }

If there's more than one bean of the same type, we can use the @Quali er annotation to reference a bean
by name:

1 public class Store {


2      
3     @Autowired
4     @Qualifier("item1")
5     private Item item;
6 }

Now, let's autowire beans by type through XML con guration:

https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 5/8
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung

1 <bean id="store" class="org.baeldung.store.Store" autowire="byType"> </bean>

Next, let's inject a bean named item into the item property of store bean by name through XML:

1 <bean id="item" class="org.baeldung.store.ItemImpl1" />


2  
3 <bean id="store" class="org.baeldung.store.Store" autowire="byName">
4 </bean>

We can also override the autowiring by de ning dependencies explicitly through constructor arguments or
setters.

9. Lazy Initialized Beans

By default, the container creates and con gures all singleton beans during initialization. To avoid this, you
can use the lazy-init attribute with value true on the bean con guration:

1 <bean id="item1" class="org.baeldung.store.ItemImpl1" lazy-init="true" />

As a consequence, the item1 bean will be initialized only when it's rst requested, and not at startup. The
advantage of this is faster initialization time, but the trade-o is that con guration errors may be discovered
only after the bean is requested, which could be several hours or even days after the application has
already been running.

10. Conclusion

In this article, we've presented the concepts of inversion of control and dependency injection and
exempli ed them in the Spring framework.
You can read more about these concepts in Martin Fowler's articles:
Inversion of Control Containers and the Dependency Injection pattern
(http://martinfowler.com/articles/injection.html).
Inversion of Control (http://martinfowler.com/bliki/InversionOfControl.html)
And you can learn more about the Spring implementations of IoC and DI in the Spring Framework
Reference Documentation (https://docs.spring.io/spring/docs/current/spring-framework-
reference/htmlsingle/#beans-dependencies).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)


https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring 6/8
9/16/2019 Project configuration with Spring | Baeldung

(/)

11AM–9PM Mumbai

Project Configuration with Spring


Last modi ed: July 29, 2019

by Eugen Paraschiv (https://www.baeldung.com/author/eugen/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

Table of Contents

1. Con guration Must Be Environment Speci c


2. The .properties les for Each Environment
3. The Spring Con guration
4. Setting the Property in Each Environment
5. Testing and Maven
6. Going Further
7. Conclusion

1. Con guration Must Be Environment Speci c

Con guration must be environment speci c – that's just a fact of life. If that weren't the case, then it
wouldn't be con guration and we would just hardcode values in code.
For a Spring application there are several solutions you can use – from simple solutions all the way to
uber- exible, highly complex alternatives.

One of more common and straightforward solutions is a exible use of properties les and the rst class
property support provided by Spring (/properties-with-spring).

https://www.baeldung.com/project-configuration-with-spring 1/5
9/16/2019 Project configuration with Spring | Baeldung

As a proof of concept, for the purposes of this article, we'll take a look at one speci c type of property – the
database con guration. It makes perfect sense to use one type of database con guration for production,
another for testing and yet another for a dev environment.

2. The .properties Files for Each Environment

Let's start our Proof of Concept – by de ning the environments we want to target:
Dev
Staging
Production
Next – let's create 3 properties les – one for each of these environments:
persistence-dev.properties
persistence-staging.properties
persistence-production.properties
In a typical Maven application, these can reside in src/main/resources, but the wherever they are, they will
need to be available on the classpath when the application is deployed.
An important sidenote – having all properties les under version control makes con guration much
more transparent and reproducible. This is in opposition to having the con gs on disk somewhere and
simply pointing Spring to them.

3. The Spring Con guration

In Spring, we'll include the correct le based on the environment:

1 <?xml version="1.0" encoding="UTF-8"?>


2 <beans xmlns="http://www.springframework.org/schema/beans (http://www.springframework.org/schema/bea
3    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance (http://www.w3.org/2001/XMLSchema-instance)"
4    xmlns:context="http://www.springframework.org/schema/context (http://www.springframework.org/sche
5    xsi:schemaLocation="http://www.springframework.org/schema/beans (http://www.springframework.org/s
6       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd (http://www.springframework.o
7       http://www.springframework.org/schema/context (http://www.springframework.org/schema/context)
8       http://www.springframework.org/schema/context/spring-context-4.0.xsd (http://www.springframewo
9  
10       <context:property-placeholder
11          location="
12          classpath*:*persistence-${envTarget}.properties" />
13  
14 </beans>

The same can of course be done with Java con guration as well:

1 @PropertySource({ "classpath:persistence-${envTarget:dev}.properties" })

This approach allows for the exibility of having multiple *.properties les for speci c, focused purposes.
For example – in our case, the persistence Spring con g imports the persistence properties – which makes
perfect sense. The security con g would import security related properties and so on.

4. Setting the Property in Each Environment


https://www.baeldung.com/project-configuration-with-spring 2/5
9/16/2019 Project configuration with Spring | Baeldung

The nal, deployable war will contain all properties les – for persistence, the three variants of
persistence-*.properties. Since the les are actually named di erently, there is no fear of accidentally
including the wrong one. We will set the envTarget variable and thus select the instance we want from the
multiple existing variants.
The envTarget variable can be set in the OS/environment or as a parameter to the JVM command line:

1 -DenvTarget=dev

5. Testing and Maven

For integration tests that need persistence enabled – we'll simply set the envTarget property in the
pom.xml:

1 <plugin>
2    <groupId>org.apache.maven.plugins</groupId>
3    <artifactId>maven-surefire-plugin</artifactId>
4    <configuration>
5       <systemPropertyVariables>
6          <envTarget>h2_test</envTarget>
7       </systemPropertyVariables>
8    </configuration>
9 </plugin>

The corresponding persistence-h2_test.properties le can be placed in src/test/resources so that it will


only be used for testing and not unnecessarily included and deployed with the war at runtime.

6. Going Further

There are several ways to build additional exibility into this solution if needed.
One such way is to use a more complex encoding for the names of the properties les, specifying not just
the environment in which they are to be used, but also more information (such as the persistence provider).
For example, we might use the following types of properties: persistence-h2.properties, persistence-
mysql.properties or, even more speci c: persistence-dev_h2.properties, persistence-
staging_mysql.properties, persistence-production_amazonRDS.properties.
The advantage of such a naming convention – and it is just a convention as nothing changes in the overall
approach – is simply transparency. It now becomes much clearer what the con guration does only by
looking at the names:

persistence-dev_h2.properties: the persistence provider for the dev environment is a lightweight, in-
memory H2 database
persistence-staging_mysql.properties: the persistence provider for the staging environment is a
MySQL instance
persistence-production_amazon_rds.propertie: the persistence provider for the production
environment is Amazon RDS

https://www.baeldung.com/project-configuration-with-spring 3/5
9/16/2019 Properties with Spring and Spring Boot | Baeldung

(/)

Properties with Spring and Spring Boot


Last modi ed: August 11, 2019

by Eugen Paraschiv (https://www.baeldung.com/author/eugen/)

Spring (https://www.baeldung.com/category/spring/) +
Spring Boot (https://www.baeldung.com/category/spring/spring-boot/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

This tutorial will show how to set up and use Properties in Spring – via Java con guration and
@PropertySource or via XML and <property-placeholder>, as well how properties work in Spring Boot.

Further reading:
Spring Expression Language Guide (https://www.baeldung.com/spring-
expression-language)
This article explores Spring Expression Language (SpEL), a powerful expression language that supports
querying and manipulating object graphs at runtime.

Read more (https://www.baeldung.com/spring-expression-language) →

2. Register a Properties File via Java Annotations

Spring 3.1 also introduces the new @PropertySource annotation, as a convenient mechanism for adding
property sources to the environment. This annotation is to be used in conjunction with Java based
con guration and the @Con guration annotation:

https://www.baeldung.com/properties-with-spring 1/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung

1 @Configuration
2 @PropertySource("classpath:foo.properties")
3 public class PropertiesWithJavaConfig {
4     //...
5 }

One other very useful way of registering a new properties le is using a placeholder to allow you to
dynamically select the right le at runtime; for example:

1 @PropertySource({
2   "classpath:persistence-${envTarget:mysql}.properties"
3 })
4 ...

2.1. De ning Multiple Property Locations

The @PropertySource annotation is repeatable according to Java 8 conventions


(https://docs.oracle.com/javase/tutorial/java/annotations/repeating.html). Therefore, if we're using Java 8
or higher, we can use this annotation to de ne multiple property locations:

1 @PropertySource("classpath:foo.properties")
2 @PropertySource("classpath:bar.properties")
3 public class PropertiesWithJavaConfig {
4     //...
5 }

Of course, we can also use the @PropertySources annotation and specify an array of @PropertySource. This
works in any supported Java version, not just in Java 8 or higher:

1 @PropertySources({
2     @PropertySource("classpath:foo.properties"),
3     @PropertySource("classpath:bar.properties")
4 })
5 public class PropertiesWithJavaConfig {
6     //...
7 }

In either case, it's worth noting that in the event of a property name collision, the last source read takes
precedence.

3. Register a Properties File in XML

In XML, new properties les can be made accessible to Spring via the <context:property-placeholder … >
namespace element:

1 <context:property-placeholder location="classpath:foo.properties" />

The foo.properties le should be placed under /src/main/resources so that it will be available on the
classpath at runtime.
In case multiple <property-placeholder> elements are present in the Spring context, there are a few
recommended best practices:
the order attribute needs to be speci ed to x the order in which these are processed by Spring
all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true”
to allow the resolution mechanism to pass to others in the context without throwing an exception

https://www.baeldung.com/properties-with-spring 2/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung

3.1. Register Multiple Properties Files in XML

In the previous section, we saw how to de ne multiple properties les using annotations in Java 8 or later.
Similarly, we can de ne multiple properties les using XML con guration:

1 <context:property-placeholder location="classpath:foo.properties, classpath:bar.properties"/>

And, as before, in the event of a property name collision, the last source read takes precedence.

4. Using / Injecting Properties

Injecting a property with the @Value annotation (https://www.baeldung.com/spring-value-annotation)


is straightforward:

1 @Value( "${jdbc.url}" )
2 private String jdbcUrl;

A default value of the property can also be speci ed:

1 @Value( "${jdbc.url:aDefaultUrl}" )
2 private String jdbcUrl;

Using properties in Spring XML con guration:

1 <bean id="dataSource">
2   <property name="url" value="${jdbc.url}" />
3 </bean>

Both the older PropertyPlaceholderCon gurer and the new PropertySourcesPlaceholderCon gurer added
in Spring 3.1 resolve ${…} placeholders within bean de nition property values and @Value annotations.
Finally – we can obtain the value of a property using the Environment API:

1 @Autowired
2 private Environment env;
3 ...
4 dataSource.setUrl(env.getProperty("jdbc.url"));

A very important caveat here is that using <property-placeholder> will not expose the properties to the
Spring Environment – this means that retrieving the value like this will not work – it will return null:

1 env.getProperty("key.something")

5. Properties with Spring Boot

Before we go into more advanced con guration options for properties, let's spend some time looking at the
new properties support in Spring Boot.
Generally speaking, this new support involves less con guration compared to standard Spring, which is, of
course, one of the main goals of Boot.

5.1. application.properties – the Default Property File

https://www.baeldung.com/properties-with-spring 3/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung

Boot applies its typical convention over con guration approach to property les. This means that we can
simply put an “application.properties” le in our “src/main/resources” directory, and it will be auto-
detected. We can then inject any loaded properties from it as normal.
So, by using this default le, we don’t have to explicitly register a PropertySource, or even provide a path to
a property le.
We can also con gure a di erent le at runtime if we need to, using an environment property:

1 java -jar app.jar --spring.config.location=classpath:/another-location.properties

5.2. Environment Speci c Properties File

If we need to target di erent environments, there's a built-in mechanism for that in Boot.
We can simply de ne an “application-environment.properties” le in the “src/main/resources” directory –
and then set a Spring pro le with the same environment name.
For example, if we de ne a “staging” environment, that means we'll have to de ne a staging pro le and then
application-staging.properties.
This env le will be loaded and will take precedence over the default property le. Note that the default
le will still be loaded, it's just that when there is a property collision the environment speci c property le
takes precedence.

5.3. Test Speci c Properties File

We might also have a requirement to use di erent property values when our application is under test.

Spring Boot handles this for us by looking in our “src/test/resources” directory during a test run. Again,
default properties will still be injectable as normal but will be overridden these ones if there is a collision.

5.4. The @TestPropertySource Annotation

If we need more granular control over test properties, then we can make use of the @TestPropertySource
(https://docs.spring.io/spring/docs/current/javadoc-
api/org/springframework/test/context/TestPropertySource.html) annotation.
This allows us to set test properties for a speci c test context, taking precedence over the default property
sources:

1 @ContextConfiguration
2 @TestPropertySource("/my-test.properties")
3 public class IntegrationTests {
4     // tests
5 }

If we don't want to use a le, we can specify names and values directly:

https://www.baeldung.com/properties-with-spring 4/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung
1 @ContextConfiguration
2 @TestPropertySource("foo=bar", "bar=foo")
3 public class IntegrationTests {
4     // tests
5 }

We can also achieve a similar e ect using the properties argument of the @SpringBootTest
(https://docs.spring.io/spring-
boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html) annotation:

1 @SpringBootTest(properties = {"foo=bar", "bar=foo"})


2 public class IntegrationTests {
3     // tests
4 }

5.5. Hierarchical Properties

If we have properties which are grouped together, we can make use of the @Con gurationProperties
(https://docs.spring.io/spring-
boot/docs/current/api/org/springframework/boot/context/properties/Con gurationProperties.html)
annotation which will map these property hierarchies into Java objects graphs.
Let's take some properties used to con gure a database connection:

1 database.url=jdbc:postgresql:/localhost:5432/instance
2 database.username=foo
3 database.password=bar

And then let's use the annotation to map them to a database object:

1 @ConfigurationProperties(prefix = "database")
2 public class Database {
3     String url;
4     String username;
5     String password;
6  
7     // standard getters and setters
8 }

Spring Boot applies it's convention over con guration approach again, automatically mapping between
property names and their corresponding elds. All that we need to supply is the property pre x.
If you want to dig deeper into con guration properties, have a look at the in-depth article (/con guration-
properties-in-spring-boot).

5.6. Alternative – YAML Files

YAML les are also supported.


All the same naming rules apply for test speci c, environment speci c, and default property les. The only
di erence is the le extension, and a dependency on the SnakeYAML
(https://bitbucket.org/asomov/snakeyaml) library being on your classpath.
YAML is particularly good for hierarchical property storage; the following property le:

1 database.url=jdbc:postgresql:/localhost:5432/instance
2 database.username=foo
3 database.password=bar
4 secret: foo

https://www.baeldung.com/properties-with-spring 5/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung

Is synonymous to the following YAML le:

1 database:
2   url: jdbc:postgresql:/localhost:5432/instance
3   username: foo
4   password: bar
5 secret: foo

It's also worth mentioning that YAML les do not support the @PropertySource annotation, so if use of the
annotation was required it would constrain us to using a properties le.

5.7. Properties from Command Line Arguments

As opposed to using les, properties can be passed directly on the command line:

1 java -jar app.jar --property="value"

You can also do this via system properties, which are provided before the -jar command rather than after it:

1 java -Dproperty.name="value" -jar app.jar

5.8. Properties from Environment Variables

Spring Boot will also detect environment variables, treating them as properties:

1 export name=value
2 java -jar app.jar

5.9 Randomization of Property Values

If we don't want determinist property values, RandomValuePropertySource (https://docs.spring.io/spring-


boot/docs/1.5.7.RELEASE/api/org/springframework/boot/context/con g/RandomValuePropertySource.
html) can be used to randomise the values of properties:

1 random.number=${random.int}
2 random.long=${random.long}
3 random.uuid=${random.uuid}

5.10. Additional Types of Property Sources

Spring Boot supports a multitude of property sources, implementing a well thought ordering to allow
sensible overriding. It's worth consulting the o cial documentation (https://docs.spring.io/spring-
boot/docs/current/reference/html/boot-features-external-con g.html), which goes further than the
scope of this article.

6. Con guration using Raw Beans in Spring 3.0 – the


PropertyPlaceholderCon gurer

Besides the convenient methods of getting properties into Spring – annotations and the XML namespace –
the property con guration bean can also be de ned and registered manually. Working with the
PropertyPlaceholderCon gurer gives us full control over the con guration, with the downside of being
more verbose and most of the time, unnecessary.
6.1. Java con guration

https://www.baeldung.com/properties-with-spring 6/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung
1 @Bean
2 public static PropertyPlaceholderConfigurer properties() {
3     PropertyPlaceholderConfigurer ppc
4       = new PropertyPlaceholderConfigurer();
5     Resource[] resources = new ClassPathResource[]
6       { new ClassPathResource( "foo.properties" ) };
7     ppc.setLocations( resources );
8     ppc.setIgnoreUnresolvablePlaceholders( true );
9     return ppc;
10 }

6.2. XML con guration

1 <bean
2   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
3     <property name="locations">
4         <list>
5             <value>classpath:foo.properties</value>
6         </list>
7     </property>
8     <property name="ignoreUnresolvablePlaceholders" value="true"/>
9 </bean>

7. Con guration using Raw Beans in Spring 3.1 – the


PropertySourcesPlaceholderCon gurer

Similarly, in Spring 3.1, the new PropertySourcesPlaceholderCon gurer can also be con gured manually:
7.1. Java con guration

1 @Bean
2 public static PropertySourcesPlaceholderConfigurer properties(){
3     PropertySourcesPlaceholderConfigurer pspc
4       = new PropertySourcesPlaceholderConfigurer();
5     Resource[] resources = new ClassPathResource[ ]
6       { new ClassPathResource( "foo.properties" ) };
7     pspc.setLocations( resources );
8     pspc.setIgnoreUnresolvablePlaceholders( true );
9     return pspc;
10 }

7.2. XML con guration

1 <bean
2   class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
3     <property name="locations">
4         <list>
5             <value>classpath:foo.properties</value>
6         </list>
7     </property>
8     <property name="ignoreUnresolvablePlaceholders" value="true"/>
9 </bean>

8. Properties in Parent-Child Contexts

This question keeps coming up again and again – what happens when your web application has a parent
and a child context? The parent context may have some common core functionality and beans, and then
one (or multiple) child contexts, maybe containing servlet speci c beans.
In that case, what's the best way to de ne properties les and include them into these contexts? What's
more – how to best retrieve these properties from Spring? Here is the simple breakdown.

https://www.baeldung.com/properties-with-spring 7/11
9/16/2019 Properties with Spring and Spring Boot | Baeldung

8.1. If the properties le is de ned in XML with <property-placeholder>

If the le is de ned in the Parent context:

@Value works in Child context: NO


@Value works in Parent context: YES
If the le is de ned in the Child context:
@Value works in Child context: YES
@Value works in Parent context: NO
Finally, as we discussed before, <property-placeholder> does not expose the properties to the
environment, so:
environment.getProperty works in either context: NO

8.2. If the properties le is de ned in Java with @PropertySource

If the le is de ned in the Parent context:


@Value works in Child context: YES
@Value works in Parent context: YES
environment.getProperty in Child context: YES
environment.getProperty in Parent context: YES
If the le is de ned in the Child context:
@Value works in Child context: YES
@Value works in Parent context: NO
environment.getProperty in Child context: YES
environment.getProperty in Parent context: NO

9. Conclusion

This article shows several examples of working with properties and properties les in Spring.
As always, the entire code backing the article is available over on Github
(https://github.com/eugenp/tutorials/tree/master/spring-boot-properties). This is a Maven based project,
so it should be easy to import and run as it is.

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:
https://www.baeldung.com/properties-with-spring 8/11
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung

(/)

Quick Guide to Spring Bean Scopes


Last modi ed: September 4, 2019

by Loredana Crusoveanu (https://www.baeldung.com/author/loredana-crusoveanu/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this quick tutorial, you'll learn about the di erent types of bean scopes in the Spring framework.
The scope of a bean de nes the life cycle and visibility of that bean in the contexts in which it is used.

Designed to Make An Impression


Lenovo Exclusive Store - Absolute IT Solutions Pvt. Ltd

The latest version of Spring framework de nes 6 types of scopes:


singleton
prototype
request
session
application
websocket
The last four scopes mentioned request, session, application and websocket are only available in a web-
aware application.

Further reading:
What is a Spring Bean? (https://www.baeldung.com/spring-bean)
A quick and practical explanation of what a Spring Bean is.

https://www.baeldung.com/spring-bean-scopes 1/8
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung
Read more (https://www.baeldung.com/spring-bean) →

Spring Bean Annotations (https://www.baeldung.com/spring-bean-


annotations)
Learn how and when to use the standard Spring bean annotations - @Component, @Repository, @Service and
@Controller.

Read more (https://www.baeldung.com/spring-bean-annotations) →

2. Singleton Scope

De ning a bean with singleton scope means the container creates a single instance of that bean, and all
requests for that bean name will return the same object, which is cached. Any modi cations to the object
will be re ected in all references to the bean. This scope is the default value if no other scope is speci ed.
Let's create a Person entity to exemplify the concept of scopes:

1 public class Person {


2     private String name;
3  
4     // standard constructor, getters and setters
5 }

Afterwards, we de ne the bean with singleton scope by using the @Scope annotation:

1 @Bean
2 @Scope("singleton")
3 public Person personSingleton() {
4     return new Person();
5 }

We can also use a constant instead of the String value in the following manner:

1 @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)

Now we proceed to write a test that shows that two objects referring to the same bean will have the same
values, even if only one of them changes their state, as they are both referencing the same bean instance:

1 private static final String NAME = "John Smith";


2  
3 @Test
4 public void givenSingletonScope_whenSetName_thenEqualNames() {
5     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
6  
7     Person personSingletonA = (Person) applicationContext.getBean("personSingleton");
8     Person personSingletonB = (Person) applicationContext.getBean("personSingleton");
9  
10     personSingletonA.setName(NAME);
11     Assert.assertEquals(NAME, personSingletonB.getName());
12  
13     ((AbstractApplicationContext) applicationContext).close();
14 }

The scopes.xml le in this example should contain the xml de nitions of the beans used:

https://www.baeldung.com/spring-bean-scopes 2/8
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans (http://www.springframework.org/schema/bean
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance (http://www.w3.org/2001/XMLSchema-instance)"
4     xsi:schemaLocation="http://www.springframework.org/schema/beans (http://www.springframework.org/s
5     http://www.springframework.org/schema/beans/spring-beans.xsd (http://www.springframework.org/sche
6  
7     <bean id="personSingleton" class="org.baeldung.scopes.Person" scope="singleton"/>   
8 </beans>

3. Prototype Scope

A bean with prototype scope will return a di erent instance every time it is requested from the container. It
is de ned by setting the value prototype to the @Scope annotation in the bean de nition:

1 @Bean
2 @Scope("prototype")
3 public Person personPrototype() {
4     return new Person();
5 }

We could also use a constant as we did for the singleton scope:

1 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)

We will now write a similar test as before that shows two objects requesting the same bean name with
scope prototype will have di erent states, as they are no longer referring to the same bean instance:

1 private static final String NAME = "John Smith";


2 private static final String NAME_OTHER = "Anna Jones";
3  
4 @Test
5 public void givenPrototypeScope_whenSetNames_thenDifferentNames() {
6     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopes.xml");
7  
8     Person personPrototypeA = (Person) applicationContext.getBean("personPrototype");
9     Person personPrototypeB = (Person) applicationContext.getBean("personPrototype");
10  
11     personPrototypeA.setName(NAME);
12     personPrototypeB.setName(NAME_OTHER);
13  
14     Assert.assertEquals(NAME, personPrototypeA.getName());
15     Assert.assertEquals(NAME_OTHER, personPrototypeB.getName());
16  
17     ((AbstractApplicationContext) applicationContext).close();
18 }

The scopes.xml le is similar to the one presented in the previous section while adding the xml de nition for
the bean with prototype scope:

1 <bean id="personPrototype" class="org.baeldung.scopes.Person" scope="prototype"/>

4. Web Aware Scopes

As mentioned, there are four additional scopes that are only available in a web-aware application context.
These are less often used in practice.

https://www.baeldung.com/spring-bean-scopes 3/8
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung

The request scope creates a bean instance for a single HTTP request while session scope creates for an
HTTP Session.
The application scope creates the bean instance for the lifecycle a ServletContext and the
websocket scope creates it for a particular WebSocket session.
Let's create a class to use for instantiating the beans:

1 public class HelloMessageGenerator {


2     private String message;
3      
4     // standard getter and setter
5 }

4.1. Request Scope

We can de ne the bean with request scope using the @Scope annotation:

1 @Bean
2 @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
3 public HelloMessageGenerator requestScopedBean() {
4     return new HelloMessageGenerator();
5 }

The proxyMode attribute is necessary because, at the moment of the instantiation of the web application
context, there is no active request. Spring will create a proxy to be injected as a dependency, and
instantiate the target bean when it is needed in a request.
Next, we can de ne a controller that has an injected reference to the requestScopedBean. We need to
access the same request twice in order to test the web speci c scopes.
If we display the message each time the request is run, we can see that the value is reset to null, even
though it is later changed in the method. This is because of a di erent bean instance being returned for
each request.

1 @Controller
2 public class ScopesController {
3     @Resource(name = "requestScopedBean")
4     HelloMessageGenerator requestScopedBean;
5  
6     @RequestMapping("/scopes/request")
7     public String getRequestScopeMessage(final Model model) {
8         model.addAttribute("previousMessage", requestScopedBean.getMessage());
9         requestScopedBean.setMessage("Good morning!");
10         model.addAttribute("currentMessage", requestScopedBean.getMessage());
11         return "scopesExample";
12     }
13 }

4.2. Session Scope

We can de ne the bean with session scope in a similar manner:

1 @Bean
2 @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
3 public HelloMessageGenerator sessionScopedBean() {
4     return new HelloMessageGenerator();
5 }

Next, we de ne a controller with a reference to the sessionScopedBean. Again, we need to run two


requests in order to show that the value of the message eld is the same for the session.
In this case, when the request is made for the rst time, the value message is null. But once, it is changed,
then that value is retained for subsequent requests as the same instance of the bean is returned for the
entire session.

https://www.baeldung.com/spring-bean-scopes 4/8
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung
1 @Controller
2 public class ScopesController {
3     @Resource(name = "sessionScopedBean")
4     HelloMessageGenerator sessionScopedBean;
5  
6     @RequestMapping("/scopes/session")
7     public String getSessionScopeMessage(final Model model) {
8         model.addAttribute("previousMessage", sessionScopedBean.getMessage());
9         sessionScopedBean.setMessage("Good afternoon!");
10         model.addAttribute("currentMessage", sessionScopedBean.getMessage());
11         return "scopesExample";
12     }
13 }

4.3. Application Scope

The application scope creates the bean instance for the lifecycle of a ServletContext.
This is similar to the singleton scope but there is a very important di erence with regards to the scope of
the bean.

When beans are application scoped the same instance of the bean is shared across multiple servlet-based
applications running in the same ServletContext, while singleton-scoped beans are scoped to a single
application context only.
Let's create the bean with application scope:

1 @Bean
2 @Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
3 public HelloMessageGenerator applicationScopedBean() {
4     return new HelloMessageGenerator();
5 }

And the controller that references this bean:

1 @Controller
2 public class ScopesController {
3     @Resource(name = "applicationScopedBean")
4     HelloMessageGenerator applicationScopedBean;
5  
6     @RequestMapping("/scopes/application")
7     public String getApplicationScopeMessage(final Model model) {
8         model.addAttribute("previousMessage", applicationScopedBean.getMessage());
9         applicationScopedBean.setMessage("Good afternoon!");
10         model.addAttribute("currentMessage", applicationScopedBean.getMessage());
11         return "scopesExample";
12     }
13 }

In this case, value message once set in the applicationScopedBean will be retained for all subsequent
requests, sessions and even for a di erent servlet application that will access this bean, provided it is
running in the same ServletContext.

https://www.baeldung.com/spring-bean-scopes 5/8
9/16/2019 Quick Guide to Spring Bean Scopes | Baeldung

4.4. WebSocket Scope

Finally, let's create the bean with websocket scope:

1 @Bean
2 @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
3 public HelloMessageGenerator websocketScopedBean() {
4     return new HelloMessageGenerator();
5 }

WebSocket-scoped beans when rst accessed are stored in the WebSocket session attributes. The same
instance of the bean is then returned whenever that bean is accessed during the entire WebSocket session.
We can also say that it exhibits singleton behavior but limited to a WebSocket session only.

5. Conclusion

We have demonstrated di erent bean scopes provided by Spring and what their intended usages are.
The implementation of this tutorial can be found in the github project
(https://github.com/eugenp/tutorials/tree/master/spring-all) – this is an Eclipse based project, so it
should be easy to import and run as it is.

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Learning to build your API


with Spring?

https://www.baeldung.com/spring-bean-scopes 6/8
9/16/2019 Spring @Qualifier Annotation | Baeldung

(/)

If you are a small


JetBrains Startup software development
team, we have a special
Offer offer for you

The Spring @Qualifier Annotation


Last modi ed: August 15, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Annotations (https://www.baeldung.com/tag/spring-annotations/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this article, we'll explore what the @Quali er annotation can help us with, which problems it solves, and
how to use it.
We'll also explain how it's di erent from the @Primary annotation and from autowiring by name.

2. Autowire Need for Disambiguation


x
The @Autowired (https://www.baeldung.com/spring-autowire) annotation is a great way of making the
need to inject a dependency in Spring explicit. And although it's useful, there are use cases for which this
annotation alone isn't enough for Spring to understand which bean to inject.
By default, Spring resolves autowired entries by type.
If more than one bean of the same type is available in the container, the framework will throw
NoUniqueBeanDe nitionException, indicating that more than one bean is available for autowiring.
Let's imagine a situation in which two possible candidates exist for Spring to inject as bean collaborators in
a given instance:

https://www.baeldung.com/spring-qualifier-annotation 1/6
9/16/2019 Spring @Qualifier Annotation | Baeldung
1 @Component("fooFormatter") x
2 public class FooFormatter implements Formatter {
3   
4     public String format() {
5         return "foo";
6     }
7 }
8  
9 @Component("barFormatter")
10 public class BarFormatter implements Formatter {
11   
12     public String format() {
13         return "bar";
14     }
15 }
16  
17 @Component
18 public class FooService {
19       
20     @Autowired
21     private Formatter formatter;
22 }

If we try to load FooService into our context, the Spring framework will throw a
NoUniqueBeanDe nitionException. This is because Spring doesn't know which bean to inject. To avoid
this problem, there are several solutions. The @Quali er annotation is one of them.

3. @Quali er Annotation

By using the @Quali er annotation, we can eliminate the issue of which bean needs to be injected.
Let's revisit our previous example and see how we solve the problem by including the @Quali er annotation
to indicate which bean we want to use:

1 public class FooService {


2       
3     @Autowired
4     @Qualifier("fooFormatter")
5     private Formatter formatter;
6 }

By including the @Quali er annotation together with the name of the speci c implementation we want to
use – in this example, Foo – we can avoid ambiguity when Spring nds multiple beans of the same type.
We need to take into consideration that the quali er name to be used is the one declared in the
@Component annotation.
Note that we could've also used the @Quali er annotation on the Formatter implementing classes, instead
of specifying the names in their @Component annotations, to obtain the same e ect:

1 @Component
2 @Qualifier("fooFormatter")
3 public class FooFormatter implements Formatter {
4     //... x
5 }
6  
7 @Component
8 @Qualifier("barFormatter")
9 public class BarFormatter implements Formatter {
10     //...
11 }

4. @Quali er vs @Primary

https://www.baeldung.com/spring-qualifier-annotation 2/6
9/16/2019 Spring @Qualifier Annotation | Baeldung

There's another annotation called @Primary (https://www.baeldung.com/spring-primary) that we can use x


to decide which bean to inject when ambiguity is present regarding dependency injection.
This annotation de nes a preference when multiple beans of the same type are present. The bean
associated with the @Primary annotation will be used unless otherwise indicated.

Let's see an example:

1 @Configuration
2 public class Config {
3   
4     @Bean
5     public Employee johnEmployee() {
6         return new Employee("John");
7     }
8   
9     @Bean
10     @Primary
11     public Employee tonyEmployee() {
12         return new Employee("Tony");
13     }
14 }

In this example, both methods return the same Employee type. The bean that Spring will inject is the one
returned by the method tonyEmployee. This is because it contains the @Primary annotation. This
annotation is useful when we want to specify which bean of a certain type should be injected by default.
And in case we require the other bean at some injection point, we would need to speci cally indicate it. We
can do that via the @Quali er annotation. For instance, we could specify that we want to use the bean
returned by the johnEmployee method by using the @Quali er annotation.
It's worth noting that if both the @Quali er and @Primary annotations are present, then the @Quali er
annotation will have precedence. Basically, @Primary de nes a default, while @Quali er is very speci c.
Let's see another way of using the @Primary annotation, this time using the initial example:

1 @Component
2 @Primary
3 public class FooFormatter implements Formatter {
4     //...
5 }
6  
7 @Component
8 public class BarFormatter implements Formatter {
9     //...
10 }

In this case, the @Primary annotation is placed in one of the implementing classes and will disambiguate
the scenario.

5. @Quali er vs Autowiring by Name

Another way to decide between multiple beans when autowiring is by using the name of the eld to inject.
This is the default in case there are no other hints for Spring. Let's see some code based on our initial
example:

1 public class FooService {


2       
3     @Autowired
4     private Formatter fooFormatter;
5 }

https://www.baeldung.com/spring-qualifier-annotation 3/6
9/16/2019 Spring @RequestParam Annotation | Baeldung

(/)

Designed to Make An Impression


Lenovo Exclusive Store - Absolute IT Solutions Pvt. Ltd

Spring @RequestParam Annotation


Last modi ed: September 4, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring MVC (https://www.baeldung.com/category/spring/spring-web/spring-mvc/)

Spring Annotations (https://www.baeldung.com/tag/spring-annotations/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)


Spring MVC Basics (https://www.baeldung.com/tag/spring-mvc-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this quick tutorial, we’ll explore Spring's @RequestParam annotation.


Simply put, we can use @RequestParam to extract query parameters, form parameters and even les
from the request.

We’ll discuss how to use @RequestParam and its attributes. We’ll also discuss the di erences between
@RequestParam and @PathVariable.

Further reading:
Spring @RequestMapping New Shortcut Annotations
(https://www.baeldung.com/spring-new-requestmapping-shortcuts)
In this article, we introduce di erent types of @RequestMapping shortcuts for quick web development using
traditional Spring MVC framework.

Read more (https://www.baeldung.com/spring-new-requestmapping-shortcuts) → x

https://www.baeldung.com/spring-request-param 1/8
9/16/2019 Spring @RequestParam Annotation | Baeldung

The Spring @Controller and @RestController Annotations x


(https://www.baeldung.com/spring-controller-vs-restcontroller)
Learn about the di erences between @Controller and @RestController annotations in Spring MVC.

Read more (https://www.baeldung.com/spring-controller-vs-restcontroller) →

2. A Simple Mapping

Let's say that we have an endpoint /api/foos that takes a query parameter called id:

1 @GetMapping("/api/foos")
2 @ResponseBody
3 public String getFoos(@RequestParam String id) {
4     return "ID: " + id;
5 }

In this example, we used @RequestParam to extract the id query parameter.


A simple GET request would invoke getFoos:

1 http://localhost:8080/api/foos?id=abc
2 ----
3 ID: abc

Next, let's have a look at the annotation's attributes: name, value, required and defaultValue.

3. Specifying the Request Parameter Name

In the previous example, both variable name and the parameter name are the same.
Sometimes we want these to be di erent, though. Or, if we aren't using Spring Boot, we may need to do
special compile-time con guration or the parameter names won't actually be in the bytecode.
But what's nice is that we can con gure the @RequestParam name using the name attribute:

1 @PostMapping("/api/foos")
2 @ResponseBody
3 public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name) {
4     return "ID: " + fooId + " Name: " + name;
5 }

We can also do @RequestParam(value = “id”) or just @RequestParam(“id”).

4. Making an Optional Request Parameter

Method parameters annotated with @RequestParam are required by default.


This means that if the parameter isn’t present in the request, we'll get an error:

1 GET /api/foos HTTP/1.1


2 -----
3 400 Bad Request
4 Required String parameter 'id' is not present
x
We can con gure our @RequestParam to be optional, though, with the required attribute:

https://www.baeldung.com/spring-request-param 2/8
9/16/2019 Spring @RequestParam Annotation | Baeldung

1 @GetMapping("/api/foos")
2 @ResponseBody
3 public String getFoos(@RequestParam(required = false) String id) {
4     return "ID: " + id;
5 }

In this case, both:

1 http://localhost:8080/api/foos?id=abc
2 ----
3 ID: abc

and

1 http://localhost:8080/api/foos
2 ----
3 ID: null

will correctly invoke the method.


When the parameter isn't speci ed, the method parameter is bound to null.

5. A Default Value for the Request Parameter

We can also set a default value to the @RequestParam by using the defaultValue attribute:

1 @GetMapping("/api/foos")
2 @ResponseBody
3 public String getFoos(@RequestParam(defaultValue = "test") String id) {
4     return "ID: " + id;
5 }

This is like required=false, in that the user no longer needs to supply the parameter:

1 http://localhost:8080/api/foos
2 ----
3 ID: test

Though, we are still okay to provide it:

1 http://localhost:8080/api/foos?id=abc
2 ----
3 ID: abc

Note that when we set the defaultValue attribute, required is, indeed, set to false.

6. Mapping All Parameters

We can also have multiple parameters without de ning their names or count by just using Map:

1 @PostMapping("/api/foos")
2 @ResponseBody
3 public String updateFoos(@RequestParam Map<String,String> allParams) { x
4     return "Parameters are " + allParams.entrySet();
5 }

https://www.baeldung.com/spring-request-param 3/8
9/16/2019 Spring @RequestParam Annotation | Baeldung

Which will then re ect back any parameters sent: x

1 curl -X POST -F 'name=abc' -F 'id=123' http://localhost:8080/api/foos


2 -----
3 Parameters are {[name=abc], [id=123]}

7. Mapping a Multi-Value Parameter

A single @RequestParam can have multiple values:

1 @GetMapping("/api/foos")
2 @ResponseBody
3 public String getFoos(@RequestParam List<String> id) {
4     return "IDs are " + id;
5 }

And Spring MVC will map a comma-delimited id parameter:

1 http://localhost:8080/api/foos?id=1,2,3
2 ----
3 IDs are [1,2,3]

Or a list of separate id parameters:

1 http://localhost:8080/api/foos?id=1&id=2
2 ----
3 IDs are [1,2]

8. @RequestParam vs @PathVariable

@RequestParam and @PathVariable can both be used to extract values from the request URI, but they are a
bit di erent.

8.1. Query Parameter vs URI Path

While @RequestParams extract values from the query string, @PathVariables extract values from the URI
path:

1 @GetMapping("/foos/{id}")
2 @ResponseBody
3 public String getFooById(@PathVariable String id) {
4     return "ID: " + id;
5 }
x
Then, we can map based on the path:

https://www.baeldung.com/spring-request-param 4/8
9/16/2019 Spring @RequestParam Annotation | Baeldung
1 http://localhost:8080/foos/abc x
2 ----
3 ID: abc

And for @RequestParam, it will be:

1 @GetMapping("/foos")
2 @ResponseBody
3 public String getFooByIdUsingQueryParam(@RequestParam String id) {
4     return "ID: " + id;
5 }

Which would give us the same response, just a di erent URI:

1 http://localhost:8080/foos?id=abc
2 ----
3 ID: abc

8.2. Encoded vs Exact Value

Because @PathVariable is extracting values from the URI path, it’s not encoded. On the other
hand, @RequestParam is.
Using the previous example, ab+c will return as-is:

1 http://localhost:8080/foos/ab+c
2 ----
3 ID: ab+c

But for a @RequestParam request, the parameter is URL decoded:

1 http://localhost:8080/foos?id=ab+c
2 ----
3 ID: ab c

8.3. Optional Values

Both @RequestParam and @PathVariable can be optional.


We can make @PathVariable optional by using the required attribute starting with Spring 4.3.3:

1 @GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})
2 @ResponseBody
3 public String getFooByOptionalId(@PathVariable(required = false) String id){
4     return "ID: " + id;
5 }

Which, then, we can do either:

1 http://localhost:8080/myfoos/optional/abc
2 ----
3 ID: abc

or:

1 http://localhost:8080/myfoos/optional
2 ----
3 ID: null

For @RequestParam, we can also use the required attribute as we saw in a previous section. x

https://www.baeldung.com/spring-request-param 5/8
9/16/2019 Spring @RequestParam Annotation | Baeldung

Note that we should be careful when making @PathVariable optional, to avoid con icts in paths.

9. Conclusion

In this article, we learned how to use @RequestParam and the di erence between @RequestParam and
@PathVariable.
The full source code for the examples can be found in the GitHub project
(https://github.com/eugenp/tutorials/tree/master/spring-mvc-simple).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

https://www.baeldung.com/spring-request-param 6/8
9/16/2019 Spring Bean Annotations | Baeldung

(/)

Spring Bean Annotations


Last modi ed: July 29, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Annotations (https://www.baeldung.com/tag/spring-annotations/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

This article is part of a series:

1. Overview

In this article, we'll discuss the most common Spring bean annotations used to de ne di erent types of
beans.
There're several ways to con gure beans in a Spring container. We can declare them using XML
con guration. We can declare beans using the @Bean annotation in a con guration class.

Lenovo Exclusive Store - Absolute IT Solutions Pvt. Ltd


10:30AM–9:30PM Mumbai

Or we can mark the class with one of the annotations from the org.springframework.stereotype package
and leave the rest to component scanning.

2. Component Scanning

Spring can automatically scan a package for beans if component scanning is enabled.
@ComponentScan con gures which packages to scan for classes with annotation con guration. We can
specify the base package names directly with one of the basePackages or value arguments (value is an
alias for basePackages):
https://www.baeldung.com/spring-bean-annotations 1/7
9/16/2019 Spring Bean Annotations | Baeldung
1 @Configuration
2 @ComponentScan(basePackages = "com.baeldung.annotations")
3 class VehicleFactoryConfig {}

Also, we can point to classes in the base packages with the basePackageClasses argument:

1 @Configuration
2 @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
3 class VehicleFactoryConfig {}

Both arguments are arrays so that we can provide multiple packages for each.
If no argument is speci ed, the scanning happens from the same package where the @ComponentScan
annotated class is present.
@ComponentScan leverages the Java 8 repeating annotations feature, which means we can mark a class
with it multiple times:

1 @Configuration
2 @ComponentScan(basePackages = "com.baeldung.annotations")
3 @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
4 class VehicleFactoryConfig {}

Alternatively, we can use @ComponentScans to specify multiple @ComponentScan con gurations:

1 @Configuration
2 @ComponentScans({
3   @ComponentScan(basePackages = "com.baeldung.annotations"),
4   @ComponentScan(basePackageClasses = VehicleFactoryConfig.class)
5 })
6 class VehicleFactoryConfig {}

When using XML con guration, the con guring component scanning is just as easy:

1 <context:component-scan base-package="com.baeldung" />

3. @Component

@Component is a class level annotation. During the component scan, Spring Framework automatically
detects classes annotated with @Component.
For example:

1 @Component
2 class CarUtility {
3     // ...
4 }

By default, the bean instances of this class have the same name as the class name with a lowercase initial.
On top of that, we can specify a di erent name using the optional value argument of this annotation.

Since @Repository, @Service, @Con guration, and @Controller are all meta-annotations of @Component,
they share the same bean naming behavior. Also, Spring automatically picks them up during the
component scanning process.

4. @Repository

https://www.baeldung.com/spring-bean-annotations 2/7
9/16/2019 Spring Bean Annotations | Baeldung

DAO or Repository classes usually represent the database access layer in an application, and should be
annotated with @Repository:

1 @Repository
2 class VehicleRepository {
3     // ...
4 }

One advantage of using this annotation is that it has automatic persistence exception translation
enabled. When using a persistence framework such as Hibernate, native exceptions thrown within classes
annotated with @Repository will be automatically translated into subclasses of Spring's
DataAccessExeption.
To enable exception translation, we need to declare our own
PersistenceExceptionTranslationPostProcessor bean:

1 @Bean
2 public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
3     return new PersistenceExceptionTranslationPostProcessor();
4 }

Note, that in most cases, Spring does the step above automatically.
Or, via XML con guration:

1 <bean class=
2   "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

5. @Service

The business logic of an application usually resides within the service layer – so we'll use the @Service
annotation to indicate that a class belongs to that layer:

1 @Service
2 public class VehicleService {
3     // ...   
4 }

6. @Controller

@Controller is a class level annotation which tells the Spring Framework that this class serves as a
controller in Spring MVC:

1 @Controller
2 public class VehicleController {
3     // ...
4 }

7. @Con guration

Con guration classes can contain bean de nition methods annotated with @Bean:

https://www.baeldung.com/spring-bean-annotations 3/7
9/16/2019 Spring Bean Annotations | Baeldung
1 @Configuration
2 class VehicleFactoryConfig {
3  
4     @Bean
5     Engine engine() {
6         return new Engine();
7     }
8  
9 }

8. Stereotype Annotations and AOP

When we use Spring stereotype annotations, it's easy to create a pointcut that targets all classes that have
a particular stereotype.
For example, suppose we want to measure the execution time of methods from the DAO layer. We'll create
the following aspect (using AspectJ annotations) taking advantage of @Repository stereotype:

1 @Aspect
2 @Component
3 public class PerformanceAspect {
4     @Pointcut("within(@org.springframework.stereotype.Repository *)")
5     public void repositoryClassMethods() {};
6  
7     @Around("repositoryClassMethods()")
8     public Object measureMethodExecutionTime(ProceedingJoinPoint joinPoint)
9       throws Throwable {
10         long start = System.nanoTime();
11         Object returnValue = joinPoint.proceed();
12         long end = System.nanoTime();
13         String methodName = joinPoint.getSignature().getName();
14         System.out.println(
15           "Execution of " + methodName + " took " +
16           TimeUnit.NANOSECONDS.toMillis(end - start) + " ms");
17         return returnValue;
18     }
19 }

In this example, we created a pointcut that matches all methods in classes annotated with @Repository. We
used the @Around advice to then target that pointcut and determine the execution time of the intercepted
methods calls.
Using this approach, we may add logging, performance management, audit, or other behaviors to each
application layer.

9. Conclusion

In this article, we have examined the Spring stereotype annotations and learned what type of semantics
these each represent.
We also learned how to use component scanning to tell the container where to nd annotated classes.

https://www.baeldung.com/spring-bean-annotations 4/7
9/16/2019 Spring Core Annotations | Baeldung

(/)

Spring Core Annotations


Last modi ed: September 1, 2019

by Attila Fejér (https://www.baeldung.com/author/attila-fejer/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Annotations (https://www.baeldung.com/tag/spring-annotations/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)


Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

This article is part of a series:

1. Overview

We can leverage the capabilities of Spring DI engine using the annotations in the
org.springframework.beans.factory.annotation and org.springframework.context.annotation packages.
We often call these “Spring core annotations” and we'll review them in this tutorial.

2. DI-Related Annotations

2.1. @Autowired

We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. We can
use this annotation with a constructor, setter, or eld injection.
Constructor injection:

https://www.baeldung.com/spring-core-annotations 1/10
9/16/2019 Spring Core Annotations | Baeldung
1 class Car {
2     Engine engine;
3  
4     @Autowired
5     Car(Engine engine) {
6         this.engine = engine;
7     }
8 }

Setter injection:

1 class Car {
2     Engine engine;
3  
4     @Autowired
5     void setEngine(Engine engine) {
6         this.engine = engine;
7     }
8 }

Field injection:

1 class Car {
2     @Autowired
3     Engine engine;
4 }

@Autowired has a boolean argument called required with a default value of true. It tunes Spring's behavior
when it doesn't nd a suitable bean to wire. When true, an exception is thrown, otherwise, nothing is wired.
Note, that if we use constructor injection, all constructor arguments are mandatory.
Starting with version 4.3, we don't need to annotate constructors with @Autowired explicitly unless we
declare at least two constructors.
For more details visit our articles about @Autowired (/spring-autowire) and constructor injection
(/constructor-injection-in-spring).

2.2. @Bean

@Bean marks a factory method which instantiates a Spring bean:

1 @Bean
2 Engine engine() {
3     return new Engine();
4 }

Spring calls these methods when a new instance of the return type is required.
The resulting bean has the same name as the factory method. If we want to name it di erently, we can do
so with the name or the value arguments of this annotation (the argument value is an alias for the argument
name):

1 @Bean("engine")
2 Engine getEngine() {
3     return new Engine();
4 }

Note, that all methods annotated with @Bean must be in @Con guration classes.

https://www.baeldung.com/spring-core-annotations 2/10
9/16/2019 Spring Core Annotations | Baeldung

2.3. @Quali er

We use @Quali er along with @Autowired to provide the bean id or bean name we want to use in
ambiguous situations.
For example, the following two beans implement the same interface:

1 class Bike implements Vehicle {}


2  
3 class Car implements Vehicle {}

If Spring needs to inject a Vehicle bean, it ends up with multiple matching de nitions. In such cases, we can
provide a bean's name explicitly using the @Quali er annotation.
Using constructor injection:

1 @Autowired
2 Biker(@Qualifier("bike") Vehicle vehicle) {
3     this.vehicle = vehicle;
4 }

Using setter injection:

1 @Autowired
2 void setVehicle(@Qualifier("bike") Vehicle vehicle) {
3     this.vehicle = vehicle;
4 }

Alternatively:

1 @Autowired
2 @Qualifier("bike")
3 void setVehicle(Vehicle vehicle) {
4     this.vehicle = vehicle;
5 }

Using eld injection:

1 @Autowired
2 @Qualifier("bike")
3 Vehicle vehicle;

For a more detailed description, please read this article (/spring-autowire).

2.4. @Required

@Required on setter methods to mark dependencies that we want to populate through XML:

1 @Required
2 void setColor(String color) {
3     this.color = color;
4 }

1 <bean class="com.baeldung.annotations.Bike">
2     <property name="color" value="green" />
3 </bean>

Otherwise, BeanInitializationException will be thrown.

2.5. @Value

https://www.baeldung.com/spring-core-annotations 3/10
9/16/2019 Spring Core Annotations | Baeldung

We can use @Value (/spring-value-annotation) for injecting property values into beans. It's compatible with
constructor, setter, and eld injection.
Constructor injection:

1 Engine(@Value("8") int cylinderCount) {


2     this.cylinderCount = cylinderCount;
3 }

Setter injection:

1 @Autowired
2 void setCylinderCount(@Value("8") int cylinderCount) {
3     this.cylinderCount = cylinderCount;
4 }

Alternatively:

1 @Value("8")
2 void setCylinderCount(int cylinderCount) {
3     this.cylinderCount = cylinderCount;
4 }

Field injection:

1 @Value("8")
2 int cylinderCount;

Of course, injecting static values isn't useful. Therefore, we can use placeholder strings in @Value to wire
values de ned in external sources, for example, in .properties or .yaml les.
Let's assume the following .properties le:

1 engine.fuelType=petrol

We can inject the value of engine.fuelType with the following:

1 @Value("${engine.fuelType}")
2 String fuelType;

We can use @Value even with SpEL. More advanced examples can be found in our article about @Value
(/spring-value-annotation).

2.6. @DependsOn

We can use this annotation to make Spring initialize other beans before the annotated one. Usually, this
behavior is automatic, based on the explicit dependencies between beans.
We only need this annotation when the dependencies are implicit, for example, JDBC driver loading or
static variable initialization.

https://www.baeldung.com/spring-core-annotations 4/10
9/16/2019 Spring Core Annotations | Baeldung

We can use @DependsOn on the dependent class specifying the names of the dependency beans. The
annotation's value argument needs an array containing the dependency bean names:

1 @DependsOn("engine")
2 class Car implements Vehicle {}

Alternatively, if we de ne a bean with the @Bean annotation, the factory method should be annotated with
@DependsOn:

1 @Bean
2 @DependsOn("fuel")
3 Engine engine() {
4     return new Engine();
5 }

2.7. @Lazy

We use @Lazy (/spring-lazy-annotation) when we want to initialize our bean lazily. By default, Spring
creates all singleton beans eagerly at the startup/bootstrapping of the application context.
However, there are cases when we need to create a bean when we request it, not at application startup.
This annotation behaves di erently depending on where we exactly place it. We can put it on:

a @Bean annotated bean factory method, to delay the method call (hence the bean creation)
a @Con guration class and all contained @Bean methods will be a ected
a @Component class, which is not a @Con guration class, this bean will be initialized lazily
an @Autowired constructor, setter, or eld, to load the dependency itself lazily (via proxy)
This annotation has an argument named value with the default value of true. It is useful to override the
default behavior.
For example, marking beans to be eagerly loaded when the global setting is lazy, or con gure speci c
@Bean methods to eager loading in a @Con guration class marked with @Lazy:

1 @Configuration
2 @Lazy
3 class VehicleFactoryConfig {
4  
5     @Bean
6     @Lazy(false)
7     Engine engine() {
8         return new Engine();
9     }
10 }

For further reading, please visit this article (/spring-lazy-annotation).

2.8. @Lookup

A method annotated with @Lookup tells Spring to return an instance of the method’s return type when we
invoke it.
Detailed information about the annotation can be found in this article (/spring-lookup).

2.9. @Primary

https://www.baeldung.com/spring-core-annotations 5/10
9/16/2019 Spring Core Annotations | Baeldung

Sometimes we need to de ne multiple beans of the same type. In these cases, the injection will be
unsuccessful because Spring has no clue which bean we need.
We already saw an option to deal with this scenario: marking all the wiring points with @Quali er and
specify the name of the required bean.
However, most of the time we need a speci c bean and rarely the others. We can use @Primary to simplify
this case: if we mark the most frequently used bean with @Primary it will be chosen on unquali ed
injection points:

1 @Component
2 @Primary
3 class Car implements Vehicle {}
4  
5 @Component
6 class Bike implements Vehicle {}
7  
8 @Component
9 class Driver {
10     @Autowired
11     Vehicle vehicle;
12 }
13  
14 @Component
15 class Biker {
16     @Autowired
17     @Qualifier("bike")
18     Vehicle vehicle;
19 }

In the previous example Car is the primary vehicle. Therefore, in the Driver class, Spring injects a Car bean.
Of course, in the Biker bean, the value of the eld vehicle will be a Bike object because it's quali ed.

2.10. @Scope

We use @Scope to de ne the scope (/spring-bean-scopes) of a @Component class or a @Bean de nition.


It can be either singleton, prototype, request, session, globalSession or some custom scope.
For example:

1 @Component
2 @Scope("prototype")
3 class Engine {}

3. Context Con guration Annotations

We can con gure the application context with the annotations described in this section.

https://www.baeldung.com/spring-core-annotations 6/10
9/16/2019 Spring Core Annotations | Baeldung

3.1. @Pro le

If we want Spring to use a @Component class or a @Bean method only when a speci c pro le is active,
we can mark it with @Pro le. We can con gure the name of the pro le with the value argument of the
annotation:

1 @Component
2 @Profile("sportDay")
3 class Bike implements Vehicle {}

You can read more about pro les in this article (/spring-pro les).

3.2. @Import

We can use speci c @Con guration classes without component scanning with this annotation. We can
provide those classes with @Import‘s value argument:

1 @Import(VehiclePartSupplier.class)
2 class VehicleFactoryConfig {}

3.3. @ImportResource

We can import XML con gurations with this annotation. We can specify the XML le locations with the
locations argument, or with its alias, the value argument:

1 @Configuration
2 @ImportResource("classpath:/annotations.xml")
3 class VehicleFactoryConfig {}

3.4. @PropertySource

With this annotation, we can de ne property les for application settings:

1 @Configuration
2 @PropertySource("classpath:/annotations.properties")
3 class VehicleFactoryConfig {}

https://www.baeldung.com/spring-core-annotations 7/10
9/16/2019 Spring Core Annotations | Baeldung

@PropertySource leverages the Java 8 repeating annotations feature, which means we can mark a class
with it multiple times:

1 @Configuration
2 @PropertySource("classpath:/annotations.properties")
3 @PropertySource("classpath:/vehicle-factory.properties")
4 class VehicleFactoryConfig {}

3.5. @PropertySources

We can use this annotation to specify multiple @PropertySource con gurations:

1 @Configuration
2 @PropertySources({
3     @PropertySource("classpath:/annotations.properties"),
4     @PropertySource("classpath:/vehicle-factory.properties")
5 })
6 class VehicleFactoryConfig {}

Note, that since Java 8 we can achieve the same with the repeating annotations feature as described
above.

4. Conclusion

In this article, we saw an overview of the most common Spring core annotations. We saw how to con gure
bean wiring and application context, and how to mark classes for component scanning.
As usual, the examples are available over on GitHub
(https://github.com/eugenp/tutorials/tree/master/spring-boot-mvc).

Next »
Spring Web Annotations (https://www.baeldung.com/spring-mvc-
annotations)

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

https://www.baeldung.com/spring-core-annotations 8/10
9/16/2019 Spring Profiles | Baeldung

(/)

Spring Profiles
Last modi ed: September 4, 2019

by Eugen Paraschiv (https://www.baeldung.com/author/eugen/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

In this article, we'll focus on introducing Pro les in Spring.


Pro les are a core feature of the framework – allowing us to map our beans to di erent pro les – for
example, dev, test, prod.

Designed to Make An Impression


Lenovo Exclusive Store - Absolute IT Solutions Pvt. Ltd

We can then activate di erent pro les in di erent environments to bootstrap just the beans we need:

Further reading:
Con guring Separate Spring DataSource for Tests
(https://www.baeldung.com/spring-testing-separate-data-source)
A quick, practical tutorial on how to con gure a separate data source for testing in a Spring application.

Read more (https://www.baeldung.com/spring-testing-separate-data-source) →

Properties with Spring and Spring Boot


(https://www.baeldung.com/properties-with-spring)
Tutorial for how to work with properties les and property values in Spring.

Read more (https://www.baeldung.com/properties-with-spring) →

https://www.baeldung.com/spring-profiles 1/11
9/16/2019 Spring Profiles | Baeldung

2. Use @Pro le on a Bean

Let's start simple and look at how we can make a bean belong to a particular pro le. Using the @Pro le
annotation – we are mapping the bean to that particular pro le; the annotation simply takes the names of
one (or multiple) pro les.
Consider a basic scenario – we have a bean that should only be active during development, but not
deployed in production. We annotate that bean with a “dev” pro le, and it will only be present in the
container during development – in production, the dev simply won't be active:

1 @Component
2 @Profile("dev")
3 public class DevDatasourceConfig

As a quick sidenote, pro le names can also be pre xed with a NOT operator e.g. “!dev” to exclude them
from a pro le.
In the below example, the component is activated only if “dev” pro le is not active:

1 @Component
2 @Profile("!dev")
3 public class DevDatasourceConfig

3. Declare Pro les in XML

Pro les can also be con gured in XML – the <beans> tag has “pro les” attribute which takes comma
separated values of the applicable pro les:

1 <beans profile="dev">
2     <bean id="devDatasourceConfig"
3       class="org.baeldung.profiles.DevDatasourceConfig" />
4 </beans>

4. Set Pro les

The next step is to activate and set the pro les so that the respective beans are registered in the container.
This can be done in a variety of ways – which we'll explore in the following sections.

4.1. Programmatically via WebApplicationInitializer interface

In web applications, WebApplicationInitializer can be used to con gure the ServletContext


programmatically.
It's also a very handy location to set our active pro les programmatically:

https://www.baeldung.com/spring-profiles 2/11
9/16/2019 Spring Profiles | Baeldung
1 @Configuration
2 public class MyWebApplicationInitializer
3   implements WebApplicationInitializer {
4  
5     @Override
6     public void onStartup(ServletContext servletContext) throws ServletException {
7   
8         servletContext.setInitParameter(
9           "spring.profiles.active", "dev");
10     }
11 }

4.2. Programmatically via Con gurableEnvironment

You can also set pro les directly on the environment:

1 @Autowired
2 private ConfigurableEnvironment env;
3 ...
4 env.setActiveProfiles("someProfile");

4.3. Context Parameter in web.xml

Similarly, pro les can be activated in the web.xml of the web application as well, using a context
parameter:

1 <context-param>
2     <param-name>contextConfigLocation</param-name>
3     <param-value>/WEB-INF/app-config.xml</param-value>
4 </context-param>
5 <context-param>
6     <param-name>spring.profiles.active</param-name>
7     <param-value>dev</param-value>
8 </context-param>

4.4. JVM System Parameter

The pro le names can also be passed in via a JVM system parameter. The pro le names passed as the
parameter will be activated during application start-up:

1 -Dspring.profiles.active=dev

4.5. Environment Variable

In a Unix environment, pro les can also be activated via the environment variable:

1 export spring_profiles_active=dev

4.6. Maven Pro le

Spring pro les can also be activated via Maven pro les, by specifying the
spring.pro les.active con guration property.

https://www.baeldung.com/spring-profiles 3/11
9/16/2019 Spring Profiles | Baeldung

In every Maven pro le, we can set a spring.pro les.active property:

1 <profiles>
2     <profile>
3         <id>dev</id>
4         <activation>
5             <activeByDefault>true</activeByDefault>
6         </activation>
7         <properties>
8             <spring.profiles.active>dev</spring.profiles.active>
9         </properties>
10     </profile>
11     <profile>
12         <id>prod</id>
13         <properties>
14             <spring.profiles.active>prod</spring.profiles.active>
15         </properties>
16     </profile>
17 </profiles>

Its value will be used to replace the @spring.pro les.active@ placeholder in application.properties:

1 [email protected]@

Now, we need to enable resource ltering in pom.xml:

1 <build>
2     <resources>
3         <resource>
4             <directory>src/main/resources</directory>
5             <filtering>true</filtering>
6         </resource>
7     </resources>
8     ...
9 </build>

And append a -P parameter to switch which Maven pro le will be applied:

1 mvn clean package -Pprod

This command will package the application for prod pro le. It also applies the spring.pro les.active value
‘prod' for this application when it is running.

4.7. @ActivePro le in Tests

Tests make it very easy to specify what pro les are active – using the @ActivePro le annotation to enable
speci c pro les:

1 @ActiveProfiles("dev")

To summarize, we looked at multiple ways of activating pro les. Let's now see which one has priority over
the other and what happens if you use more than one – from highest to lowest priority:
1. Context parameter in web.xml
2. WebApplicationInitializer
3. JVM System parameter
4. Environment variable
5. Maven pro le

5. The Default Pro le

Any bean that does not specify a pro le belongs to “default” pro le.
https://www.baeldung.com/spring-profiles 4/11
9/16/2019 Spring Profiles | Baeldung

Spring also provides a way to set the default pro le when no other pro le is active – by using the
“spring.pro les.default” property.

6. Get Active Pro les

Spring's active pro les drive the behavior of the @Pro le annotation for enabling/disabling beans. However,
we may also wish to access the list of active pro les programmatically.

We have two ways to do it, using Environment or spring.active.pro le.

6.1. Using Environment

We can access the active pro les from the Environment object by injecting it:

1 public class ProfileManager {


2     @Autowired
3     private Environment environment;
4  
5     public void getActiveProfiles() {
6         for (String profileName : environment.getActiveProfiles()) {
7             System.out.println("Currently active profile - " + profileName);
8         }  
9     }
10 }

6.2. Using spring.active.pro le

Alternatively, we could access the pro les by injecting the property spring.pro les.active:

1 @Value("${spring.profiles.active}")
2 private String activeProfile;

Here, our activePro le variable will contain the name of the pro le that is currently active, and if there are
several, it'll contain their names separated by a comma.
However, we should consider what would happen if there is no active pro le at all. With our code above,
the absence of an active pro le would prevent the application context from being created. This would
result in an IllegalArgumentException owing to the missing placeholder for injecting into the variable.
In order to avoid this, we can de ne a default value:

1 @Value("${spring.profiles.active:}")
2 private String activeProfile;

Now, if no pro les are active, our activePro le will just contain an empty string. And, if we want to access
the list of them just like in the previous example, we can do it by splitting (https://www.baeldung.com/java-
split-string) the activePro le variable:

https://www.baeldung.com/spring-profiles 5/11
9/16/2019 Spring Profiles | Baeldung
1 public class ProfileManager {
2     @Value("${spring.profiles.active:}")
3     private String activeProfiles;
4  
5     public String getActiveProfiles() {
6         for (String profileName : activeProfiles.split(",")) {
7             System.out.println("Currently active profile - " + profileName);
8         }
9     }
10 }

7. Example of Using Pro les

Now that the basics are out of the way, let's take a look at a real example.
Consider a scenario where we have to maintain the datasource con guration for both the development and
production environments. Let's create a common interface DatasourceCon g that needs to be
implemented by both data source implementations:

1 public interface DatasourceConfig {


2     public void setup();
3 }

Following is the con guration for the development environment:

1 @Component
2 @Profile("dev")
3 public class DevDatasourceConfig implements DatasourceConfig {
4     @Override
5     public void setup() {
6         System.out.println("Setting up datasource for DEV environment. ");
7     }
8 }

And con guration for the production environment:

1 @Component
2 @Profile("production")
3 public class ProductionDatasourceConfig implements DatasourceConfig {
4     @Override
5     public void setup() {
6        System.out.println("Setting up datasource for PRODUCTION environment. ");
7     }
8 }

Now let's create a test and inject our DatasourceCon g interface; depending on the active pro le, Spring
will inject DevDatasourceCon g or ProductionDatasourceCon g bean:

1 public class SpringProfilesWithMavenPropertiesIntegrationTest {


2     @Autowired
3     DatasourceConfig datasourceConfig;
4  
5     public void setupDatasource() {
6         datasourceConfig.setup();
7     }
8 }

When the “dev” pro le is active spring injects DevDatasourceCon g object, and on call of setup() method
following is the output:

https://www.baeldung.com/spring-profiles 6/11
9/16/2019 Spring Profiles | Baeldung
1 Setting up datasource for DEV environment.

8. Pro les in Spring Boot

Spring Boot supports all the pro le con guration outlined so far, with a few additional features.
The initialization parameter spring.pro les.active, introduced in section 4, can also be set up as a property in
Spring Boot to de ne currently active pro les. This is a standard property that Spring Boot will pick up
automatically:

1 spring.profiles.active=dev

To set pro les programmatically, we can also use the SpringApplication class:

1 SpringApplication.setAdditionalProfiles("dev");

To set pro les using Maven in Spring Boot, we can specify pro le names under spring-boot-maven-plugin
in pom.xml:

1 <plugins>
2     <plugin>
3         <groupId>org.springframework.boot</groupId>
4         <artifactId>spring-boot-maven-plugin</artifactId>
5         <configuration>
6             <profiles>
7                 <profile>dev</profile>
8             </profiles>
9         </configuration>
10     </plugin>
11     ...
12 </plugins>

And execute the Spring Boot speci c Maven goal:

1 mvn spring-boot:run

But the most important pro les-related feature that Spring Boot brings is pro le-speci c properties les.
These have to be named in the format applications-{pro le}.properties.
Spring Boot will automatically load the properties in an application.properties le for all pro les, and the
ones in pro le-speci c .properties les only for the speci ed pro le.
For example, we can con gure di erent data sources for dev and production pro les by using two les
named application-dev.properties and application-production.properties:
In the application-production.properties le, we can set up a MySql data source:

1 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2 spring.datasource.url=jdbc:mysql://localhost:3306/db (mysql://localhost:3306/db)
3 spring.datasource.username=root
4 spring.datasource.password=root

Then, we can con gure the same properties for the dev pro le in the application-dev.properties le, to use
an in-memory H2 database:

1 spring.datasource.driver-class-name=org.h2.Driver
2 spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
3 spring.datasource.username=sa
4 spring.datasource.password=sa

In this way, we can easily provide di erent con gurations for di erent environments.

https://www.baeldung.com/spring-profiles 7/11
9/16/2019 Understanding getBean() in Spring | Baeldung

(/)

Understanding getBean() in Spring


Last modi ed: July 29, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/)

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Introduction

In this tutorial, we're going to go through di erent variants of the BeanFactory.getBean() method.
Simply put, as the name of the method also suggests, this is responsible for retrieving a bean instance
from the Spring container.

2. Spring Beans Setup

First, let's de ne a few Spring beans for testing. There are several ways in which we can provide bean
de nitions for the Spring container, but in our example, we'll use annotation-based Java con g:

https://www.baeldung.com/spring-getbean 1/5
9/16/2019 Understanding getBean() in Spring | Baeldung
1 @Configuration x
2 class AnnotationConfig {
3  
4     @Bean(name = {"tiger", "kitty"})
5     @Scope(value = "prototype")
6     Tiger getTiger(String name) {
7         return new Tiger(name);
8     }
9  
10     @Bean(name = "lion")
11     Lion getLion() {
12         return new Lion("Hardcoded lion name");
13     }
14  
15     interface Animal {}
16 }

We've created two beans. Lion has the default singleton scope. Tiger is explicitly set to prototype scope
(https://www.baeldung.com/spring-bean-scopes). Additionally, please note that we de ned names for
each bean that we'll use in further requests.

3. The getBean() APIs

BeanFactory (https://www.baeldung.com/spring-beanfactory) provides ve di erent signatures of the


getBean() method that we're going to examine in the following subsections.

3.1. Retrieving Bean by Name

Let's see how we can retrieve a Lion bean instance using its name:

1 Object lion = context.getBean("lion");


2  
3 assertEquals(Lion.class, lion.getClass());

In this variant, we provide a name, and in return, we get an instance of Object class if a bean with the given
name exists in the application context. Otherwise, both this and all other implementations throw
NoSuchBeanDe nitionException (https://www.baeldung.com/spring-nosuchbeande nitionexception) if the
bean lookup fails.
The main disadvantage is that after retrieving the bean, we have to cast it to the desired type
(https://www.baeldung.com/java-type-casting). This may produce another exception if the returned
bean has a di erent type than we expected.
Suppose we try to get a Tiger using the name “lion”.  When we cast the result to Tiger, it will throw a
ClassCastException:

1 assertThrows(ClassCastException.class, () -> {
2     Tiger tiger = (Tiger) context.getBean("lion");
3 });

3.2. Retrieving Bean by Name and Type

Here we need to specify both the name and type of the requested bean:

1 Lion lion = context.getBean("lion", Lion.class);

Compared to the previous method, this one is safer because we get the information about type mismatch
instantly: x

https://www.baeldung.com/spring-getbean 2/5
9/16/2019 Understanding getBean() in Spring | Baeldung
1 assertThrows(BeanNotOfRequiredTypeException.class, () -> x
2     context.getBean("lion", Tiger.class));
3 }

3.3. Retrieving Bean by Type

With the third variant of getBean(), it is enough to specify only the bean type:

1 Lion lion = context.getBean(Lion.class);

In this case, we need to pay special attention to a potentially ambiguous outcome:

1 assertThrows(NoUniqueBeanDefinitionException.class, () ->
2     context.getBean(Animal.class));
3 }

In the example above, because both Lion and Tiger implement the Animal interface, merely specifying type
isn't enough to unambiguously determine the result. Therefore, we get a
NoUniqueBeanDe nitionException.

3.4. Retrieving Bean by Name with Constructor Parameters

In addition to the bean name, we can also pass constructor parameters:

1 Tiger tiger = (Tiger) context.getBean("tiger", "Siberian");

This method is a bit di erent because it only applies to beans with prototype scope.
In the case of singletons, we're going to get a BeanDe nitionStoreException
(https://www.baeldung.com/spring-beande nitionstoreexception).
Because a prototype bean will return a newly created instance every time it's requested from the
application container, we can provide constructor parameters on-the- y when invoking getBean():

1 Tiger tiger = (Tiger) context.getBean("tiger", "Siberian");


2 Tiger secondTiger = (Tiger) context.getBean("tiger", "Striped");
3  
4 assertEquals("Siberian", tiger.getName());
5 assertEquals("Striped", secondTiger.getName());

As we can see, each Tiger gets a di erent name according to what we speci ed as a second parameter
when requesting the bean.

3.5. Retrieving Bean by Type With Constructor Parameters

This method is analogous to the last one, but we need to pass the type instead of the name as the rst
argument:

1 Tiger tiger = context.getBean(Tiger.class, "Shere Khan");


2  
3 assertEquals("Shere Khan", tiger.getName());

x
Similar to retrieving a bean by name with constructor parameters, this method only applies to beans with
prototype scope.

https://www.baeldung.com/spring-getbean 3/5
9/16/2019 Using Spring @Value with Defaults | Baeldung

(/)

Using Spring @Value with Defaults


Last modi ed: August 11, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

Spring's @Value annotation provides a convenient way to inject property values into components. It's also
quite useful to provide sensible defaults for cases where a property may not be present.
That's what we're going to be focusing on in this article – how to specify a default value for the @Value
Spring annotation. For a more detailed quick guide on @Value, see the article here (/spring-value-
annotation).

2. String Defaults

Let's look at the basic syntax for setting a default value for a String property:

1 @Value("${some.key:my default value}")


2 private String stringWithDefaultValue;

If some.key cannot be resolved, then stringWithDefaultValue will be set to the default value of “my default
value”.
Similarly, we can set a zero-length String as the default value:

1 @Value("${some.key:})"
2 private String stringWithBlankDefaultValue;

https://www.baeldung.com/spring-value-defaults 1/4
9/16/2019 Using Spring @Value with Defaults | Baeldung

3. Primitives

To set a default value for primitive types such as boolean and int, we use the literal value:

1 @Value("${some.key:true}")
2 private boolean booleanWithDefaultValue;

1 @Value("${some.key:42}")
2 private int intWithDefaultValue;

If we wanted to, we could use primitive wrappers instead by changing the types to Boolean and Integer.

4. Arrays

We can also inject a comma-separated list of values into an array:

1 @Value("${some.key:one,two,three}")
2 private String[] stringArrayWithDefaults;
3  
4 @Value("${some.key:1,2,3}")
5 private int[] intArrayWithDefaults;

In the rst example above, the values “one”, “two”, and “three” are injected as defaults into
stringArrayWithDefaults.
In the second example, the values 1, 2, and 3 are injected as defaults into intArrayWithDefaults.

5. Using SpEL

We can also use Spring Expression Language (SpEL) to specify an expression and a default.
In the example below, we expect some.system.key to be set as a system property, and if it is not set, we
want to use “my default system property value” as a default:

1 @Value("#{systemProperties['some.key'] ?: 'my default system property value'}")


2 private String spelWithDefaultValue;

6. Conclusion

In this quick article, we looked at how we can set a default value for a property whose value we would like
to have injected using Spring's @Value annotation.
As usual, all the code samples used in this article can found in the GitHub project
(https://github.com/eugenp/tutorials/tree/master/spring-boot-properties).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:
https://www.baeldung.com/spring-value-defaults 2/4
9/16/2019 What is a Spring Bean? | Baeldung

(/)

What is a Spring Bean?


Last modi ed: September 4, 2019

by Nguyen Nam Thai (https://www.baeldung.com/author/namthai-nguyen/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

Bean is a key concept of the Spring Framework. As such, understanding this notion is crucial to get the
hang of the framework and to use it in an e ective way.
Unfortunately, there aren't clear answers to a simple question – what a Spring bean really is. Some
explanations go to such a low level that a big picture is missed, whereas some are too vague.

Crocs Men
Beige Casual …
Rs. 4,495

Crocs Men Beige Casual Shoes - 204967...

Rs. 4,495

Shop Now

This tutorial will try to shed light on the topic, starting with a description in the o cial documentation.

Further reading:
https://www.baeldung.com/spring-bean 1/6
9/16/2019
g What is a Spring Bean? | Baeldung

Why Choose Spring as Your Java Framework?


(https://www.baeldung.com/spring-why-to-choose)
A quick and practical overview of the main value proposition of Spring framework.

Read more (https://www.baeldung.com/spring-why-to-choose) →

Understanding getBean() in Spring (https://www.baeldung.com/spring-


getbean)
Learn about the di erent variants of Spring's BeanFactory.getBean() method for retrieving a bean instance from
the Spring container

Read more (https://www.baeldung.com/spring-getbean) →

2. Bean De nition

Here's a de nition of beans in the Spring Framework documentation


(https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-introduction):
In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC
container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by
a Spring IoC container.
This de nition is concise and gets to the point, but misses an important thing – Spring IoC container. Let's
go down the rabbit hole to see what it is and the bene ts it brings in.

3. Inversion of Control

Simply put, I (https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring)nversion


of Control (https://www.baeldung.com/inversion-control-and-dependency-injection-in-spring), or IoC for
short, is a process in which an object de nes its dependencies without creating them. This object
delegates the job of constructing such dependencies to an IoC container.
Let's start with the declaration of a couple of domain classes before diving into IoC.

3.1. Domain Classes

Assume we have a class declaration:

1 public class Company {


2     private Address address;
3  
4     public Company(Address address) {
5         this.address = address;
6     }
7  
8     // getter, setter and other properties
9 }

This class needs a collaborator of type Address:

https://www.baeldung.com/spring-bean 2/6
9/16/2019 What is a Spring Bean? | Baeldung
1 public class Address {
2     private String street;
3     private int number;
4  
5     public Address(String street, int number) {
6         this.street = street;
7         this.number = number;
8     }
9  
10     // getters and setters
11 }

3.2. Traditional Approach

Normally, we create objects with their classes' constructors:

1 Address address = new Address("High Street", 1000);


2 Company company = new Company(address);

There's nothing wrong with this approach, but wouldn't it be nice to manage the dependencies in a better
way?
Imagine an application with dozens or even hundreds of classes. Sometimes we want to share a single
instance of a class across the whole application, other times we need a separate object for each use case,
and so on.
Managing such a number of objects is nothing short of a nightmare. This is where Inversion of Control
comes to the rescue.

Instead of constructing dependencies by itself, an object can retrieve its dependencies from an IoC
container. All we need to do is to provide the container with appropriate con guration metadata.

3.3. Bean Con guration

First o , let's decorate the Company class with the @Component annotation:

1 @Component
2 public class Company {
3     // this body is the same as before
4 }

Here's a con guration class supplying bean metadata to an IoC container:

1 @Configuration
2 @ComponentScan(basePackageClasses = Company.class)
3 public class Config {
4     @Bean
5     public Address getAddress() {
6         return new Address("High Street", 1000);
7     }
8 }

The con guration class produces a bean of type Address. It also carries the @ComponentScan annotation,
which instructs the container to looks for beans in the package containing the Company class.
When a Spring IoC container constructs objects of those types, all the objects are called Spring beans
as they are managed by the IoC container.

https://www.baeldung.com/spring-bean 3/6
9/16/2019 What is a Spring Bean? | Baeldung

3.4. IoC in Action

Since we de ned beans in a con guration class, we'll need an instance of the
AnnotationCon gApplicationContext class to build up a container:

1 ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

A quick test veri es the existence as well as property values of our beans:

1 Company company = context.getBean("company", Company.class);


2 assertEquals("High Street", company.getAddress().getStreet());
3 assertEquals(1000, company.getAddress().getNumber());

The result proves that the IoC container has created and initialized beans correctly.

4. Conclusion

This tutorial gave a brief description of Spring beans and their relationship with an IoC container.
The complete source code for this tutorial can be found over on GitHub
(https://github.com/eugenp/tutorials/tree/master/spring-core).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Learning to build your API


with Spring?

https://www.baeldung.com/spring-bean 4/6
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

(/)

Wiring in Spring: @Autowired, @Resource


and @Inject
Last modi ed: July 29, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)


Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Overview

This Spring Framework article will demonstrate the use of annotations related to dependency injection,
namely the @Resource, @Inject, and @Autowired annotations. These annotations provide classes with a
declarative way to resolve dependencies. For example:

1 @Autowired
2 ArbitraryClass arbObject;

as opposed to instantiating them directly (the imperative way), for example:

Amazon Brand - Solimo Premium Almonds, 500g


(599)
Rs. 469.00 (details + delivery) Rs. 93.80 / 100 g

1 ArbitraryClass arbObject = new ArbitraryClass();

https://www.baeldung.com/spring-annotations-resource-inject-autowire 1/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

Two of the three annotations belong to the Java extension package: javax.annotation.Resource and
javax.inject.Inject. The @Autowired annotation belongs to the org.springframework.beans.factory.annotation
package.
Each of these annotations can resolve dependencies either by eld injection or by setter injection. A
simpli ed, but practical example will be used to demonstrate the distinction between the three
annotations, based on the execution paths taken by each annotation.
The examples will focus on how to use the three injection annotations during integration testing. The
dependency required by the test can either be an arbitrary le or an arbitrary class.

2. The @Resource Annotation

The @Resource annotation is part of the JSR-250 (https://jcp.org/en/jsr/detail?id=250) annotation


collection and is packaged with Java EE. This annotation has the following execution paths, listed by
precedence:
1. Match by Name
2. Match by Type
3. Match by Quali er
These execution paths are applicable to both setter and eld injection.

2.1. Field Injection

Resolving dependencies by eld injection is achieved by annotating an instance variable with the
@Resource annotation.
2.1.1. Match by Name

The integration test used to demonstrate match-by-name eld injection is listed as follows:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestResourceNameType.class)
5 public class FieldResourceInjectionTest {
6  
7     @Resource(name="namedFile")
8     private File defaultFile;
9  
10     @Test
11     public void givenResourceAnnotation_WhenOnField_ThenDependencyValid(){
12         assertNotNull(defaultFile);
13         assertEquals("namedFile.txt", defaultFile.getName());
14     }
15 }

Let's go through the code. In the FieldResourceInjectionTest integration test, at line 7, the resolution of the
dependency by name is achieved by passing in the bean name as an attribute value to the @Resource
annotation:

1 @Resource(name="namedFile")
2 private File defaultFile;

This con guration will resolve dependencies using the match-by-name execution path. The bean
namedFile must be de ned in the ApplicationContextTestResourceNameType application context.
Note that the bean id and the corresponding reference attribute value must match:
https://www.baeldung.com/spring-annotations-resource-inject-autowire 2/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @Configuration
2 public class ApplicationContextTestResourceNameType {
3  
4     @Bean(name="namedFile")
5     public File namedFile() {
6         File namedFile = new File("namedFile.txt");
7         return namedFile;
8     }
9 }

Failure to de ne the bean in the application context will result in a


org.springframework.beans.factory.NoSuchBeanDe nitionException being thrown. This can be
demonstrated by changing the attribute value passed into the @Bean annotation, in the
ApplicationContextTestResourceNameType application context; or changing the attribute value passed into
the @Resource annotation, in the FieldResourceInjectionTest integration test.
2.1.2. Match by Type
To demonstrate the match-by-type execution path, just remove the attribute value at line 7 of the
FieldResourceInjectionTest integration test so that it looks as follows:

1 @Resource
2 private File defaultFile;

and run the test again.


The test will still pass because if the @Resource annotation does not receive a bean name as an attribute
value, the Spring Framework will proceed with the next level of precedence, match-by-type, in order to try
resolve the dependency.
2.1.3. Match by Quali er
To demonstrate the match-by-quali er execution path, the integration testing scenario will be modi ed so
that there are two beans de ned in the ApplicationContextTestResourceQuali er application context:

1 @Configuration
2 public class ApplicationContextTestResourceQualifier {
3  
4     @Bean(name="defaultFile")
5     public File defaultFile() {
6         File defaultFile = new File("defaultFile.txt");
7         return defaultFile;
8     }
9  
10     @Bean(name="namedFile")
11     public File namedFile() {
12         File namedFile = new File("namedFile.txt");
13         return namedFile;
14     }
15 }

The Quali erResourceInjectionTest integration test will be used to demonstrate match-by-quali er


dependency resolution. In this scenario, a speci c bean dependency needs to be injected into each
reference variable:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 3/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestResourceQualifier.class)
5 public class QualifierResourceInjectionTest {
6  
7     @Resource
8     private File dependency1;
9      
10     @Resource
11     private File dependency2;
12  
13     @Test
14     public void givenResourceAnnotation_WhenField_ThenDependency1Valid(){
15         assertNotNull(dependency1);
16         assertEquals("defaultFile.txt", dependency1.getName());
17     }
18  
19     @Test
20     public void givenResourceQualifier_WhenField_ThenDependency2Valid(){
21         assertNotNull(dependency2);
22         assertEquals("namedFile.txt", dependency2.getName());
23     }
24 }

Run the integration test, and an org.springframework.beans.factory.NoUniqueBeanDe nitionException is


thrown. This exception is thrown because the application context has found two bean de nitions of type
File, and it is confused as to which bean should resolve the dependency.
To resolve this issue, please refer to line 7 to line 10 of the Quali erResourceInjectionTest integration test:

1 @Resource
2 private File dependency1;
3  
4 @Resource
5 private File dependency2;

and add the following lines of code:

1 @Qualifier("defaultFile")
2  
3 @Qualifier("namedFile")

so that the code block looks as follows:

1 @Resource
2 @Qualifier("defaultFile")
3 private File dependency1;
4  
5 @Resource
6 @Qualifier("namedFile")
7 private File dependency2;

Run the integration test again, this time round it should pass. The objective of this test was to demonstrate
that even if there are multiple beans de ned in an application context, the @Quali er annotation clears any
confusion by allowing speci c dependencies to be injected into a class.

2.2. Setter Injection

The execution paths taken when injecting dependencies on a eld are applicable to setter-based injection.
2.2.1. Match by Name
The only di erence is the MethodResourceInjectionTest integration test has a setter method:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 4/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestResourceNameType.class)
5 public class MethodResourceInjectionTest {
6  
7     private File defaultFile;
8  
9     @Resource(name="namedFile")
10     protected void setDefaultFile(File defaultFile) {
11         this.defaultFile = defaultFile;
12     }
13  
14     @Test
15     public void givenResourceAnnotation_WhenSetter_ThenDependencyValid(){
16         assertNotNull(defaultFile);
17         assertEquals("namedFile.txt", defaultFile.getName());
18     }
19 }

Resolving dependencies by setter injection is done by annotating a reference variable's corresponding


setter method. Pass the name of the bean dependency as an attribute value to the @Resource annotation:

1 private File defaultFile;


2  
3 @Resource(name="namedFile")
4 protected void setDefaultFile(File defaultFile) {
5     this.defaultFile = defaultFile;
6 }

The namedFile bean dependency will be reused in this example. The bean name and the corresponding
attribute value must match.
Run the integration test as-is and it will pass.
To see that the dependency was indeed resolved by the match-by-name execution path, change the
attribute value passed to the @Resource annotation to a value of your choice and run the test again. This
time, the test will fail with a NoSuchBeanDe nitionException.
2.2.2. Match by Type
To demonstrate setter-based, match-by-type execution, we will use the MethodByTypeResourceTest
integration test:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 5/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestResourceNameType.class)
5 public class MethodByTypeResourceTest {
6  
7     private File defaultFile;
8  
9     @Resource
10     protected void setDefaultFile(File defaultFile) {
11         this.defaultFile = defaultFile;
12     }
13  
14     @Test
15     public void givenResourceAnnotation_WhenSetter_ThenValidDependency(){
16         assertNotNull(defaultFile);
17         assertEquals("namedFile.txt", defaultFile.getName());
18     }
19 }

Run this test as-is, and it will pass.


In order to verify that the File dependency was indeed resolved by the match-by-type execution path,
change the class type of the defaultFile variable to another class type like String. Execute the
MethodByTypeResourceTest integration test again and this time a NoSuchBeanDe nitionException will be
thrown.
The exception veri es that match-by-type was indeed used to resolve the File dependency. The
NoSuchBeanDe nitionException con rms that the reference variable name does not need to match the
bean name. Instead, dependency resolution depends on the bean's class type matching the reference
variable's class type.
2.2.3. Match by Quali er
The MethodByQuali erResourceTest integration test will be used to demonstrate the match-by-quali er
execution path:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestResourceQualifier.class)
5 public class MethodByQualifierResourceTest {
6  
7     private File arbDependency;
8     private File anotherArbDependency;
9  
10     @Test
11     public void givenResourceQualifier_WhenSetter_ThenValidDependencies(){
12       assertNotNull(arbDependency);
13         assertEquals("namedFile.txt", arbDependency.getName());
14         assertNotNull(anotherArbDependency);
15         assertEquals("defaultFile.txt", anotherArbDependency.getName());
16     }
17  
18     @Resource
19     @Qualifier("namedFile")
20     public void setArbDependency(File arbDependency) {
21         this.arbDependency = arbDependency;
22     }
23  
24     @Resource
25     @Qualifier("defaultFile")
26     public void setAnotherArbDependency(File anotherArbDependency) {
27         this.anotherArbDependency = anotherArbDependency;
28     }
29 }

The objective of this test is to demonstrate that even if multiple bean implementations of a particular type
are de ned in an application context, a @Quali er annotation can be used together with the @Resource
annotation to resolve a dependency.

https://www.baeldung.com/spring-annotations-resource-inject-autowire 6/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

Similar to eld-based dependency injection, if there are multiple beans de ned in an application context, a
NoUniqueBeanDe nitionException is thrown if no @Quali er annotation is used to specify which bean
should be used to resolve dependencies.

3. The @Inject Annotation

The @Inject annotation belongs to the JSR-330 (https://jcp.org/en/jsr/detail?id=330) annotations collection.


This annotation has the following execution paths, listed by precedence:
1. Match by Type
2. Match by Quali er
3. Match by Name
These execution paths are applicable to both setter and eld injection. In order to access the @Inject
annotation, the javax.inject library has to be declared as a Gradle or Maven dependency.
For Gradle:

1 testCompile group: 'javax.inject', name: 'javax.inject', version: '1'

For Maven:

1 <dependency>
2     <groupId>javax.inject</groupId>
3     <artifactId>javax.inject</artifactId>
4     <version>1</version>
5 </dependency>

3.1. Field Injection

3.1.1. Match by Type


The integration test example will be modi ed to use another type of dependency, namely the
ArbitraryDependency class. The ArbitraryDependency class dependency merely serves as a simple
dependency and holds no further signi cance. It is listed as follows:

1 @Component
2 public class ArbitraryDependency {
3  
4     private final String label = "Arbitrary Dependency";
5  
6     public String toString() {
7         return label;
8     }
9 }

The FieldInjectTest integration test in question is listed as follows:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 7/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestInjectType.class)
5 public class FieldInjectTest {
6  
7     @Inject
8     private ArbitraryDependency fieldInjectDependency;
9  
10     @Test
11     public void givenInjectAnnotation_WhenOnField_ThenValidDependency(){
12         assertNotNull(fieldInjectDependency);
13         assertEquals("Arbitrary Dependency",
14           fieldInjectDependency.toString());
15     }
16 }

Unlike the @Resource annotation, which resolves dependencies by name rst; the default behavior of the
@Inject annotation resolves dependencies by type.
This means that even if a class reference variable name di ers from the bean name, the dependency will
still be resolved, provided that the bean is de ned in the application context. Note how the reference
variable name in the following test:

1 @Inject
2 private ArbitraryDependency fieldInjectDependency;

di ers from the bean name con gured in the application context:

1 @Bean
2 public ArbitraryDependency injectDependency() {
3     ArbitraryDependency injectDependency = new ArbitraryDependency();
4     return injectDependency;
5 }

and when the test is executed, it is able to resolve the dependency.


3.1.2. Match by Quali er
But what if there are multiple implementations of a particular class type, and a certain class requires a
speci c bean? Let us modify the integration testing example so that another dependency is required.
In this example, we subclass the ArbitraryDependency class, used in the match-by-type example, to create
the AnotherArbitraryDependency class:

1 public class AnotherArbitraryDependency extends ArbitraryDependency {


2  
3     private final String label = "Another Arbitrary Dependency";
4  
5     public String toString() {
6         return label;
7     }
8 }

The objective of each test case is to ensure that each dependency is injected correctly into each reference
variable:

1 @Inject
2 private ArbitraryDependency defaultDependency;
3  
4 @Inject
5 private ArbitraryDependency namedDependency;

The FieldQuali erInjectTest integration test used to demonstrate match by quali er is listed as follows:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 8/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestInjectQualifier.class)
5 public class FieldQualifierInjectTest {
6  
7     @Inject
8     private ArbitraryDependency defaultDependency;
9  
10     @Inject
11     private ArbitraryDependency namedDependency;
12  
13     @Test
14     public void givenInjectQualifier_WhenOnField_ThenDefaultFileValid(){
15         assertNotNull(defaultDependency);
16         assertEquals("Arbitrary Dependency",
17           defaultDependency.toString());
18     }
19  
20     @Test
21     public void givenInjectQualifier_WhenOnField_ThenNamedFileValid(){
22         assertNotNull(defaultDependency);
23         assertEquals("Another Arbitrary Dependency",
24           namedDependency.toString());
25     }
26 }

If there are multiple implementations of a particular class in an application context and the
FieldQuali erInjectTest integration test attempts to inject the dependencies in the manner listed below:

1 @Inject
2 private ArbitraryDependency defaultDependency;
3  
4 @Inject
5 private ArbitraryDependency namedDependency;

a NoUniqueBeanDe nitionException will be thrown.


Throwing this exception is the Spring Framework's way of pointing out that there are multiple
implementations of a certain class and it is confused about which one to use. In order to elucidate the
confusion, go to line 7 and 10 of the FieldQuali erInjectTest integration test:

1 @Inject
2 private ArbitraryDependency defaultDependency;
3  
4 @Inject
5 private ArbitraryDependency namedDependency;

pass the required bean name to the @Quali er annotation, which is used together with the @Inject
annotation. The code block will now look as follows:

1 @Inject
2 @Qualifier("defaultFile")
3 private ArbitraryDependency defaultDependency;
4  
5 @Inject
6 @Qualifier("namedFile")
7 private ArbitraryDependency namedDependency;

The @Quali er annotation expects a strict match when receiving a bean name. Ensure that the bean name
is passed to the Quali er correctly, otherwise, a NoUniqueBeanDe nitionException will be thrown. Run the
test again, and this time it should pass.
3.1.3. Match by Name
The FieldByNameInjectTest integration test used to demonstrate match by name is similar to the match by
type execution path. The only di erence is now a speci c bean is required, as opposed to a speci c type. In
this example, we subclass the ArbitraryDependency class again to produce the
YetAnotherArbitraryDependency class:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 9/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 public class YetAnotherArbitraryDependency extends ArbitraryDependency {
2  
3     private final String label = "Yet Another Arbitrary Dependency";
4  
5     public String toString() {
6         return label;
7     }
8 }

In order to demonstrate the match-by-name execution path, we will use the following integration test:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestInjectName.class)
5 public class FieldByNameInjectTest {
6  
7     @Inject
8     @Named("yetAnotherFieldInjectDependency")
9     private ArbitraryDependency yetAnotherFieldInjectDependency;
10  
11     @Test
12     public void givenInjectQualifier_WhenSetOnField_ThenDependencyValid(){
13         assertNotNull(yetAnotherFieldInjectDependency);
14         assertEquals("Yet Another Arbitrary Dependency",
15           yetAnotherFieldInjectDependency.toString());
16     }
17 }

The application context is listed as follows:

1 @Configuration
2 public class ApplicationContextTestInjectName {
3  
4     @Bean
5     public ArbitraryDependency yetAnotherFieldInjectDependency() {
6         ArbitraryDependency yetAnotherFieldInjectDependency =
7           new YetAnotherArbitraryDependency();
8         return yetAnotherFieldInjectDependency;
9     }
10 }

Run the integration test as-is, and it will pass.


In order to verify that the dependency was indeed injected by the match-by-name execution path, change
the value, yetAnotherFieldInjectDependency, that was passed in to the @Named annotation to another
name of your choice. Run the test again – this time, a NoSuchBeanDe nitionException is thrown.

3.2. Setter Injection

Setter-based injection for the @Inject annotation is similar to the approach used for @Resource setter-
based injection. Instead of annotating the reference variable, the corresponding setter method is annotated.
The execution paths followed by eld-based dependency injection also apply to setter based injection.

4. The @Autowired Annotation

The behaviour of @Autowired annotation is similar to the @Inject annotation. The only di erence is that the
@Autowired annotation is part of the Spring framework. This annotation has the same execution paths as
the @Inject annotation, listed in order of precedence:
1. Match by Type
2. Match by Quali er
3. Match by Name

https://www.baeldung.com/spring-annotations-resource-inject-autowire 10/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

These execution paths are applicable to both setter and eld injection.

4.1. Field Injection

4.1.1. Match by Type


The integration testing example used to demonstrate the @Autowired match-by-type execution path will
be similar to the test used to demonstrate the @Inject match-by-type execution path. The
FieldAutowiredTest integration test used to demonstrate match-by-type using the @Autowired annotation
is listed as follows:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestAutowiredType.class)
5 public class FieldAutowiredTest {
6  
7     @Autowired
8     private ArbitraryDependency fieldDependency;
9  
10     @Test
11     public void givenAutowired_WhenSetOnField_ThenDependencyResolved() {
12         assertNotNull(fieldDependency);
13         assertEquals("Arbitrary Dependency", fieldDependency.toString());
14     }
15 }

The application context for this integration test is listed as follows:

1 @Configuration
2 public class ApplicationContextTestAutowiredType {
3  
4     @Bean
5     public ArbitraryDependency autowiredFieldDependency() {
6         ArbitraryDependency autowiredFieldDependency =
7           new ArbitraryDependency();
8         return autowiredFieldDependency;
9     }
10 }

The objective of the integration test is to demonstrate that match-by-type takes rst precedence over the
other execution paths. Notice on line 8 of the FieldAutowiredTest integration test how the reference
variable name:

1 @Autowired
2 private ArbitraryDependency fieldDependency;

is di erent to the bean name in the application context:

1 @Bean
2 public ArbitraryDependency autowiredFieldDependency() {
3     ArbitraryDependency autowiredFieldDependency =
4       new ArbitraryDependency();
5     return autowiredFieldDependency;
6 }

When the test is run, it will pass.


In order to con rm that the dependency was indeed resolved using the match-by-type execution path,
change the type of the eldDependency reference variable and run the integration test again. This time
round the FieldAutowiredTest integration test must fail, with a NoSuchBeanDe nitionException being
thrown. This veri es that match-by-type was used to resolve the dependency.
4.1.2. Match by Quali er
What if faced with a situation where multiple bean implementations have been de ned in the application
context, like the one listed below:

https://www.baeldung.com/spring-annotations-resource-inject-autowire 11/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
1 @Configuration
2 public class ApplicationContextTestAutowiredQualifier {
3  
4     @Bean
5     public ArbitraryDependency autowiredFieldDependency() {
6         ArbitraryDependency autowiredFieldDependency =
7           new ArbitraryDependency();
8         return autowiredFieldDependency;
9     }
10  
11     @Bean
12     public ArbitraryDependency anotherAutowiredFieldDependency() {
13         ArbitraryDependency anotherAutowiredFieldDependency =
14           new AnotherArbitraryDependency();
15         return anotherAutowiredFieldDependency;
16     }
17 }

If the FieldQuali erAutowiredTest integration test, listed below, is executed:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestAutowiredQualifier.class)
5 public class FieldQualifierAutowiredTest {
6  
7     @Autowired
8     private ArbitraryDependency fieldDependency1;
9  
10     @Autowired
11     private ArbitraryDependency fieldDependency2;
12  
13     @Test
14     public void givenAutowiredQualifier_WhenOnField_ThenDep1Valid(){
15         assertNotNull(fieldDependency1);
16         assertEquals("Arbitrary Dependency", fieldDependency1.toString());
17     }
18  
19     @Test
20     public void givenAutowiredQualifier_WhenOnField_ThenDep2Valid(){
21         assertNotNull(fieldDependency2);
22         assertEquals("Another Arbitrary Dependency",
23           fieldDependency2.toString());
24     }
25 }

a NoUniqueBeanDe nitionException will be thrown.


The exception is due to the ambiguity caused by the two beans de ned in the application context. The
Spring Framework does not know which bean dependency should be autowired to which reference
variable. Resolve this issue by adding the @Quali er annotation to lines 7 and 10 of the
FieldQuali erAutowiredTest integration test:

1 @Autowired
2 private FieldDependency fieldDependency1;
3  
4 @Autowired
5 private FieldDependency fieldDependency2;

so that the code block looks as follows:

1 @Autowired
2 @Qualifier("autowiredFieldDependency")
3 private FieldDependency fieldDependency1;
4  
5 @Autowired
6 @Qualifier("anotherAutowiredFieldDependency")
7 private FieldDependency fieldDependency2;

Run the test again, and this time it will pass.

https://www.baeldung.com/spring-annotations-resource-inject-autowire 12/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
4.1.3. Match by Name
The same integration test scenario will be used to demonstrate the match-by-name execution path when
using the @Autowired annotation to inject a eld dependency. When autowiring dependencies by name,
the @ComponentScan annotation must be used with the application context,
ApplicationContextTestAutowiredName:

1 @Configuration
2 @ComponentScan(basePackages={"com.baeldung.dependency"})
3     public class ApplicationContextTestAutowiredName {
4 }

The @ComponentScan annotation will search packages for Java classes that have been annotated with the
@Component annotation. For example, in the application context, the com.baeldung.dependency package
will be scanned for classes that have been annotated with the @Component annotation. In this scenario,
the Spring Framework must detect the ArbitraryDependency class, which has the @Component annotation:

1 @Component(value="autowiredFieldDependency")
2 public class ArbitraryDependency {
3  
4     private final String label = "Arbitrary Dependency";
5  
6     public String toString() {
7         return label;
8     }
9 }

The attribute value, autowiredFieldDependency, passed into the @Component annotation, tells the Spring
Framework that the ArbitraryDependency class is a component named autowiredFieldDependency. In
order for the @Autowired annotation to resolve dependencies by name, the component name must
correspond with the eld name de ned in the FieldAutowiredNameTest integration test; please refer to line
8:

1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(
3   loader=AnnotationConfigContextLoader.class,
4   classes=ApplicationContextTestAutowiredName.class)
5 public class FieldAutowiredNameTest {
6  
7     @Autowired
8     private ArbitraryDependency autowiredFieldDependency;
9  
10     @Test
11     public void givenAutowiredAnnotation_WhenOnField_ThenDepValid(){
12         assertNotNull(autowiredFieldDependency);
13         assertEquals("Arbitrary Dependency",
14           autowiredFieldDependency.toString());
15     }
16 }

When the FieldAutowiredNameTest integration test is run as-is, it will pass.


But how do we know that the @Autowired annotation really did invoke the match-by-name execution path?
Change the name of the reference variable autowiredFieldDependency to another name of your choice,
then run the test again.
This time, the test will fail and a NoUniqueBeanDe nitionException is thrown. A similar check would be to
change the @Component attribute value, autowiredFieldDependency, to another value of your choice and
run the test again. A NoUniqueBeanDe nitionException will also be thrown.
This exception is proof that if an incorrect bean name is used, no valid bean will be found. Therefore, the
match-by-name execution path was invoked.

4.2. Setter Injection

https://www.baeldung.com/spring-annotations-resource-inject-autowire 13/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

Setter-based injection for the @Autowired annotation is similar the approach demonstrated for @Resource
setter-based injection. Instead of annotating the reference variable with the @Inject annotation, the
corresponding setter is annotated. The execution paths followed by eld-based dependency injection also
apply to setter-based injection.

5. Applying These Annotations

This raises the question, which annotation should be used and under what circumstances? The answer to
these questions depends on the design scenario faced by the application in question, and how the
developer wishes to leverage polymorphism based on the default execution paths of each annotation.

5.1. Application-Wide use of Singletons Through Polymorphism

If the design is such that application behaviors are based on implementations of an interface or an abstract
class, and these behaviors are used throughout the application, then use either the @Inject or @Autowired
annotation.
The bene t of this approach is that when the application is upgraded, or a patch needs to be applied in
order to x a bug; then classes can be swapped out with minimal negative impact to the overall application
behavior. In this scenario, the primary default execution path is match-by-type.

5.2. Fine-Grained Application Behavior Con guration Through Polymorphism

If the design is such that the application has complex behavior, each behavior is based on di erent
interfaces/abstract classes, and usage of each of these implementations varies across the application, then
use the @Resource annotation. In this scenario, the primary default execution path is match-by-name.

5.3. Dependency Injection Should be Handled Solely by the Java EE Platform

If there is a design mandate for all dependencies to be injected by the Java EE Platform and not Spring,
then the choice is between the @Resource annotation and the @Inject annotation. You should narrow down
the nal decision between the two annotations, based on which default execution path is required.

5.4. Dependency Injection Should be Handled Solely by the Spring


Framework

If the mandate is for all dependencies to be handled by the Spring Framework, the only choice is the
@Autowired annotation.

5.5. Discussion Summary

The table below summarizes the discussion.

Scenario @Resource @Inject @Autowired

Application-wide use of singletons through polymorphism ✗ ✔ ✔


Fine-grained application behavior con guration through
✔ ✗ ✗
polymorphism
Dependency injection should be handled solely by the Java
✔ ✔ ✗
EE platform

https://www.baeldung.com/spring-annotations-resource-inject-autowire 14/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung

Dependency injection should be handled solely by the


✗ ✗ ✔
Spring Framework

6. Conclusion

The article aimed to provide a deeper insight into the behavior of each annotation. Understanding how
each annotation behaves will contribute to better overall application design and maintenance.
The code used during the discussion can be found on GitHub
(https://github.com/eugenp/tutorials/tree/master/spring-core).

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Comments are closed on this article!

CATEGORIES

SPRING (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTPS://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)
JACKSON (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JSON/JACKSON/)
HTTP CLIENT-SIDE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/HTTP/)
KOTLIN (HTTPS://WWW.BAELDUNG.COM/CATEGORY/KOTLIN/)

SERIES

JAVA “BACK TO BASICS” TUTORIAL (/JAVA-TUTORIAL)


JACKSON JSON TUTORIAL (/JACKSON)
HTTPCLIENT 4 TUTORIAL (/HTTPCLIENT-GUIDE)
REST WITH SPRING TUTORIAL (/REST-WITH-SPRING-SERIES)
SPRING PERSISTENCE TUTORIAL (/PERSISTENCE-WITH-SPRING-SERIES)
SECURITY WITH SPRING (/SECURITY-SPRING)

https://www.baeldung.com/spring-annotations-resource-inject-autowire 15/16
9/16/2019 XML-Based Injection in Spring | Baeldung

(/)

XML-Based Injection in Spring


Last modi ed: July 29, 2019

by baeldung (https://www.baeldung.com/author/baeldung/)

Spring (https://www.baeldung.com/category/spring/) +

Spring Core Basics (https://www.baeldung.com/tag/spring-core-basics/)

Spring DI (https://www.baeldung.com/tag/spring-di/)

I just announced the new Learn Spring course, focused on the fundamentals of
Spring 5 and Spring Boot 2:
>> CHECK OUT THE COURSE (/ls-course-start)

1. Introduction

In this basic tutorial, we’ll learn how to do simple XML-based bean con guration with the Spring
Framework.

2. Overview

Let's start by adding Spring's library dependency in the pom.xml:

1 <dependency>
2     <groupId>org.springframework</groupId>
3     <artifactId>spring-context</artifactId>
4     <version>5.1.4.RELEASE</version>        
5 </dependency>

The latest version of the Spring dependency can be found here


(https://search.maven.org/classic/#search%7Cga%7C1%7Cg%3A%22org.springframework%22%20AND%20a
%3A%22spring-context%22).

https://www.baeldung.com/spring-xml-injection 1/5
9/16/2019 XML-Based Injection in Spring | Baeldung

3. Dependency Injection – An Overview

Dependency injection (/inversion-control-and-dependency-injection-in-spring) is a technique whereby


dependencies of an object are supplied by external containers.
Let's say we've got an application class that depends on a service that actually handles the business logic:

1 public class IndexApp {


2     private IService service;
3     // standard constructors/getters/setters
4 }

Now let's say IService is an Interface:

1 public interface IService {


2     public String serve();
3 }

This interface can have multiple implementations.


Let's have a quick look at one potential implementation:

1 public class IndexService implements IService {


2     @Override
3     public String serve() {
4         return "Hello World";
5     }
6 }

Here, IndexApp is a high-level component that depends on the low-level component called IService.

In essence, we're decoupling IndexApp from a particular implementation of the IService which can vary
based on the various factors.

4. Dependency Injection – In Action

Let's see how we can inject a dependency.

4.1. Using Properties

Let's see how we can wire the dependencies together using an XML-based con guration:

1 <bean
2   id="indexService"
3   class="com.baeldung.di.spring.IndexService" />
4       
5 <bean
6   id="indexApp"
7   class="com.baeldung.di.spring.IndexApp" >
8     <property name="service" ref="indexService" />
9 </bean>   

As can be seen, we're creating an instance of IndexService and assigning it an id. By default, the bean is a
singleton. Also, we're creating an instance of IndexApp.
Within this bean, we're injecting the other bean using setter method.

https://www.baeldung.com/spring-xml-injection 2/5
9/16/2019 XML-Based Injection in Spring | Baeldung

4.2. Using Constructor

Instead of injecting a bean via the setter method, we can inject the dependency using the constructor:

1 <bean
2   id="indexApp"
3   class="com.baeldung.di.spring.IndexApp">
4     <constructor-arg ref="indexService" />
5 </bean>   

4.3. Using Static Factory

We can also inject a bean returned by a factory. Let's create a simple factory that returns an instance of
IService based on the number supplied:

1 public class StaticServiceFactory {


2     public static IService getNumber(int number) {
3         // ...
4     }
5 }

Now let's see how we could use above implementation to inject a bean into IndexApp using an XML-based
con guration:

1 <bean id="messageService"
2   class="com.baeldung.di.spring.StaticServiceFactory"
3   factory-method="getService">
4     <constructor-arg value="1" />
5 </bean>  
6    
7 <bean id="indexApp" class="com.baeldung.di.spring.IndexApp">
8     <property name="service" ref="messageService" />
9 </bean>

In the above example, we're calling the static getService method using factory-method to create a bean
with id messageService which we inject into IndexApp.

4.4. Using Factory Method

Let's consider an instance factory that returns an instance of IService based on the number supplied. This
time, the method is not static:

1 public class InstanceServiceFactory {


2     public IService getNumber(int number) {
3         // ...
4     }
5 }

Now let's see how we could use above implementation to inject a bean into IndexApp using XML
con guration:
https://www.baeldung.com/spring-xml-injection 3/5
9/16/2019 XML-Based Injection in Spring | Baeldung
1 <bean id="indexServiceFactory"
2   class="com.baeldung.di.spring.InstanceServiceFactory" />
3 <bean id="messageService"
4   class="com.baeldung.di.spring.InstanceServiceFactory"
5   factory-method="getService" factory-bean="indexServiceFactory">
6     <constructor-arg value="1" />
7 </bean> 
8 <bean id="indexApp" class="com.baeldung.di.spring.IndexApp">
9     <property name="service" ref="messageService" />
10 </bean>

In the above example, we're calling the getService method on an instance of InstanceServiceFactory using
factory-method to create a bean with id messageService which we inject in IndexApp.

5. Testing

This is how we can access con gured beans:

1 @Test
2 public void whenGetBeans_returnsBean() {
3     ApplicationContext applicationContext = new ClassPathXmlApplicationContext("...");
4     IndexApp indexApp = applicationContext.getBean("indexApp", IndexApp.class);
5     assertNotNull(indexApp);
6 }

6. Conclusion

In this quick tutorial, we illustrated examples of how we can inject dependency using the XML-based
con guration using Spring Framework.
The implementation of these examples can be found in the GitHub project
(https://github.com/eugenp/tutorials/tree/master/spring-core) – this is a Maven-based project, so it
should be easy to import and run as is.

I just announced the new Learn Spring course, focused on the


fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE (/ls-course-end)

Comments are closed on this article!

CATEGORIES

SPRING (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SPRING/)
REST (HTTPS://WWW.BAELDUNG.COM/CATEGORY/REST/)
JAVA (HTTPS://WWW.BAELDUNG.COM/CATEGORY/JAVA/)
SECURITY (HTTPS://WWW.BAELDUNG.COM/CATEGORY/SECURITY-2/)
PERSISTENCE (HTTPS://WWW.BAELDUNG.COM/CATEGORY/PERSISTENCE/)

https://www.baeldung.com/spring-xml-injection 4/5

You might also like