Annotation-based configuration
In the previous section, we saw the two bean configuration techniques, Java-based and XML-based. Both the techniques inject dependency explicitly. In Java-based, we use the @Bean annotated method in the AppConfig Java file whereas, in XML-based, we use the <bean> element tag in the XML configuration file. Annotation-based configuration is another way of creating a bean, where we can move the bean configuration into the component class itself using annotations on the relevant class, method, or field declaration. Here, we will look at how we can configure a bean through annotation, and the different annotations available in Spring Framework.
Annotation-based configuration is turned off by default in Spring, so first, you have to turn it on by entering the <context:annotation-config/> element into the Spring XML file shown as follows. After adding it, you are ready to use annotations in your code.
The changes required to be made in applicationContext.xml (as we have used it the earlier section) are highlighted as follows:
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enable Annotation based configuration -->
<context:annotation-config />
<context:component-scan base-package="com.packt.springhighperformance.ch2.bankingapp.model"/><context:component-scan base- package="com.packt.springhighperformance.ch2.bankingapp.service"/>
<!-- Bean Configuration definition describe here -->
<bean class=""/>
</beans>
An XML-based configuration will override annotations because an XML-based configuration will be injected after annotations.
The previous XML-based configuration shows that once you configure the <context:annotation-config/> element, it indicates start of annotating your code. Spring should automatically scan the package defined in <context:component-scan base-package=".." /> and identify beans and wire them based on the pattern. Let's understand a few of the important annotations, and how they work.