Activating annotation-based configuration

Annotation-based configuration is not turned on by default. You need to enable it by defining the <context:annotation-config/> element in application context (XML) files. When Spring reads this element, it activates the actions for all annotations defined in beans in the same application context where this element is defined. In other words, Spring will activate the annotation on all the beans defined in the current application context where the <context:annotation-config /> element is defined. 

Let's update the configuration and rerun the previous code. You will get output similar to the following:

// Updated Configuration
<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">

<context:annotation-config />
<bean id="professor" class="com.packet.spring.annotation.di.Professor">
<property name="name" value="Nilang" />
</bean>

<bean id="subject" class="com.packet.spring.annotation.di.Subject">
</bean>
</beans>

//Output
...
INFO: Loading XML bean definitions from class path resource [application-context.xml]
Object of Professor is created
Object of Subject is created
setting the professor through setter method injection
This subject is taught by Nilang
To enable <context:annotation-config /> in Spring XML configuration files, you need to include a few schema definitions specific to context, such as xmlns:context, and add context-specific xsd into schemaLocation.

Now everything works as expected. Objects of the professor bean are injected into objects of the subject bean properly. This is what we want to achieve with annotation. But wait a minute. We just removed one element (<property>) and added the new one—<context:annotation-config />

Ideally, annotation-based configuration should replace XML-based configuration completely. In previous cases, we are still defining the <bean> definition in XML-based configuration. If you remove it, Spring will not create any bean, and will not perform any action for annotation you defined for those beans. This is because <context:annotation-config /> only works for the <bean>s that are defined in Spring's application context (XML) file. So, if there is no <bean> defined, there is no meaning of annotation, even though you defined it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.186.46