Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Spring's annotation-based configuration


May 14, 2021 Spring


Table of contents


Annotation-based configuration

From Spring 2.5 on, you can use annotations to configure dependency injection. Instead of using XML to describe a bean wire, you can use annotations declared by related classes, methods, or fields to move the bean configuration to the component class itself.

Annotation injections are made before XML injection, so the latter configuration is override by the former through two property lines.

Annotation connections are not turned on in the Spring container by default. T herefore, before we can use annotation-based connectivity, we will need to enable it in our Spring profile. So if you want any annotations to be used in a Spring application, consider the following configuration file.


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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <!-- bean definitions go here -->

</beans>

Once configured, you can start annotation your code, indicating that Spring should automatically connect values to properties, methods, and constructors. Let's take a look at a few important annotations and see how they work:

Serial number Notes and descriptions
1 @Required

@Required the setter method that applies the annotation to the bean property.

2 @Autowired

@Autowired can be applied to setter methods, non-setter methods, constructors, and properties of the bean property.

3 @Qualifier

By specifying the exact bean that will be connected, @Autowired and @Qualifier can be used to remove confusion.

4 JSR-250 Annotations

Spring supports the basic annotations for the JSR-250, which include @Resource, @PostConstruct, @PreDestroy and comments.