Baeldung 1
Baeldung 1
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
https://www.baeldung.com/spring-component-repository-service 3/4
9/16/2019 A Quick Guide to Spring @Value | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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.
https://www.baeldung.com/spring-value-annotation 1/5
9/16/2019 A Quick Guide to Spring @Value | Baeldung
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:
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;
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;
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:
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;
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:
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).
https://www.baeldung.com/spring-value-annotation 4/5
9/16/2019 Constructor Dependency Injection in Spring | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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.
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
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);
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.
Another way to con gure Spring runtime with constructor-based dependency injection is to use an xml
con guration le:
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.
5. Conclusion
This quick tutorial has showcased the basics of two distinct ways to use Constructor-Based Dependency
Injection using Spring framework.
https://www.baeldung.com/constructor-injection-in-spring 3/5
9/16/2019 Guide to Spring @Autowired | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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
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
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.
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.
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 }
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:
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:
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.
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 }
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:
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.
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.
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.
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
https://www.baeldung.com/spring-autowire 6/7
9/16/2019 Inversion of Control and Dependency Injection with Spring | Baeldung
(/)
Spring (https://www.baeldung.com/category/spring/) +
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.
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
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.
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:
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:
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
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.
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:
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:
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.
In case of Field-Based DI, we can inject the dependencies by marking them with an @Autowired
annotation:
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
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:
If there's more than one bean of the same type, we can use the @Quali er annotation to reference a bean
by name:
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
Next, let's inject a bean named item into the item property of store bean by name through XML:
We can also override the autowiring by de ning dependencies explicitly through constructor arguments or
setters.
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:
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).
(/)
11AM–9PM Mumbai
Spring (https://www.baeldung.com/category/spring/) +
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
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.
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.
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.
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
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>
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
(/)
Spring (https://www.baeldung.com/category/spring/) +
Spring Boot (https://www.baeldung.com/category/spring/spring-boot/)
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.
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 ...
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.
In XML, new properties les can be made accessible to Spring via the <context:property-placeholder … >
namespace element:
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
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:
And, as before, in the event of a property name collision, the last source read takes precedence.
1 @Value( "${jdbc.url}" )
2 private String jdbcUrl;
1 @Value( "${jdbc.url:aDefaultUrl}" )
2 private String jdbcUrl;
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")
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.
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:
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.
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.
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:
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).
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
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.
As opposed to using les, properties can be passed directly on the command line:
You can also do this via system properties, which are provided before the -jar command rather than after it:
Spring Boot will also detect environment variables, treating them as properties:
1 export name=value
2 java -jar app.jar
1 random.number=${random.int}
2 random.long=${random.long}
3 random.uuid=${random.uuid}
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.
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 }
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>
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 }
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>
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
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.
(/)
Spring (https://www.baeldung.com/category/spring/) +
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.
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) →
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:
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:
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 }
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:
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:
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:
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 }
1 @Bean
2 @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
3 public HelloMessageGenerator sessionScopedBean() {
4 return new HelloMessageGenerator();
5 }
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 }
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 }
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
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.
https://www.baeldung.com/spring-bean-scopes 6/8
9/16/2019 Spring @Qualifier Annotation | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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.
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:
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
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.
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:
https://www.baeldung.com/spring-qualifier-annotation 3/6
9/16/2019 Spring @RequestParam Annotation | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
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
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.
https://www.baeldung.com/spring-request-param 1/8
9/16/2019 Spring @RequestParam Annotation | Baeldung
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 }
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.
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 }
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 }
1 http://localhost:8080/api/foos?id=abc
2 ----
3 ID: abc
and
1 http://localhost:8080/api/foos
2 ----
3 ID: null
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
1 http://localhost:8080/api/foos?id=abc
2 ----
3 ID: abc
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
1 @GetMapping("/api/foos")
2 @ResponseBody
3 public String getFoos(@RequestParam List<String> id) {
4 return "IDs are " + id;
5 }
1 http://localhost:8080/api/foos?id=1,2,3
2 ----
3 IDs are [1,2,3]
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.
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
1 @GetMapping("/foos")
2 @ResponseBody
3 public String getFooByIdUsingQueryParam(@RequestParam String id) {
4 return "ID: " + id;
5 }
1 http://localhost:8080/foos?id=abc
2 ----
3 ID: abc
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
1 http://localhost:8080/foos?id=ab+c
2 ----
3 ID: ab c
1 @GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"})
2 @ResponseBody
3 public String getFooByOptionalId(@PathVariable(required = false) String id){
4 return "ID: " + id;
5 }
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).
https://www.baeldung.com/spring-request-param 6/8
9/16/2019 Spring Bean Annotations | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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 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.
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 {}
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:
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 }
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 (https://www.baeldung.com/category/spring/) +
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
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
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:
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 }
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 }
1 @Autowired
2 @Qualifier("bike")
3 Vehicle vehicle;
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>
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:
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
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 }
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
1 @Component
2 @Scope("prototype")
3 class Engine {}
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
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
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)
https://www.baeldung.com/spring-core-annotations 8/10
9/16/2019 Spring Profiles | Baeldung
(/)
Spring Profiles
Last modi ed: September 4, 2019
Spring (https://www.baeldung.com/category/spring/) +
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
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.
https://www.baeldung.com/spring-profiles 1/11
9/16/2019 Spring Profiles | Baeldung
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
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>
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.
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 }
1 @Autowired
2 private ConfigurableEnvironment env;
3 ...
4 env.setActiveProfiles("someProfile");
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>
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
In a Unix environment, pro les can also be activated via the environment variable:
1 export spring_profiles_active=dev
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
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>
1 <build>
2 <resources>
3 <resource>
4 <directory>src/main/resources</directory>
5 <filtering>true</filtering>
6 </resource>
7 </resources>
8 ...
9 </build>
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.
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
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.
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 can access the active pro les from the Environment object by injecting it:
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 }
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 @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 }
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:
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.
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>
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
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/)
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.
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.
Let's see how we can retrieve a Lion bean instance using its name:
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 });
Here we need to specify both the name and type of the requested bean:
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 }
With the third variant of getBean(), it is enough to specify only the bean type:
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.
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():
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.
This method is analogous to the last one, but we need to pass the type instead of the name as the rst
argument:
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
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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:
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
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:
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).
(/)
Spring (https://www.baeldung.com/category/spring/) +
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
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
2. Bean De nition
3. Inversion of Control
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 }
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.
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 }
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
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:
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).
https://www.baeldung.com/spring-bean 4/6
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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;
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.
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 }
1 @Resource
2 private File defaultFile;
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 }
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 }
1 @Resource
2 private File dependency1;
3
4 @Resource
5 private File dependency2;
1 @Qualifier("defaultFile")
2
3 @Qualifier("namedFile")
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.
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 }
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 }
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.
For Maven:
1 <dependency>
2 <groupId>javax.inject</groupId>
3 <artifactId>javax.inject</artifactId>
4 <version>1</version>
5 </dependency>
1 @Component
2 public class ArbitraryDependency {
3
4 private final String label = "Arbitrary Dependency";
5
6 public String toString() {
7 return label;
8 }
9 }
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 }
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;
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 }
1 @Configuration
2 public class ApplicationContextTestInjectName {
3
4 @Bean
5 public ArbitraryDependency yetAnotherFieldInjectDependency() {
6 ArbitraryDependency yetAnotherFieldInjectDependency =
7 new YetAnotherArbitraryDependency();
8 return yetAnotherFieldInjectDependency;
9 }
10 }
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.
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.
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 }
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;
1 @Bean
2 public ArbitraryDependency autowiredFieldDependency() {
3 ArbitraryDependency autowiredFieldDependency =
4 new ArbitraryDependency();
5 return autowiredFieldDependency;
6 }
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 }
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 }
1 @Autowired
2 private FieldDependency fieldDependency1;
3
4 @Autowired
5 private FieldDependency fieldDependency2;
1 @Autowired
2 @Qualifier("autowiredFieldDependency")
3 private FieldDependency fieldDependency1;
4
5 @Autowired
6 @Qualifier("anotherAutowiredFieldDependency")
7 private FieldDependency fieldDependency2;
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 }
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.
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.
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.
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.
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.
If the mandate is for all dependencies to be handled by the Spring Framework, the only choice is the
@Autowired annotation.
https://www.baeldung.com/spring-annotations-resource-inject-autowire 14/16
9/16/2019 Wiring in Spring: @Autowired, @Resource and @Inject | Baeldung
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).
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
https://www.baeldung.com/spring-annotations-resource-inject-autowire 15/16
9/16/2019 XML-Based Injection in Spring | Baeldung
(/)
by baeldung (https://www.baeldung.com/author/baeldung/)
Spring (https://www.baeldung.com/category/spring/) +
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
1 <dependency>
2 <groupId>org.springframework</groupId>
3 <artifactId>spring-context</artifactId>
4 <version>5.1.4.RELEASE</version>
5 </dependency>
https://www.baeldung.com/spring-xml-injection 1/5
9/16/2019 XML-Based Injection in Spring | Baeldung
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.
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
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>
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:
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.
Let's consider an instance factory that returns an instance of IService based on the number supplied. This
time, the method is not static:
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
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.
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