XML Configuration with Java Annotations

Learn how to use a combination of XML context and Java annotations.

In the last lesson, we removed all Java annotations from our application and used the appContext.xml file to define beans and inject the dependency. However, if we want to detect beans defined by the @Component annotation and inject the dependencies using @Autowired annotation while using XML context, we can do that too.

In large projects, declaring a lot of beans using the <bean> tag is cumbersome, so annotation-based dependency injection was introduced in Spring 2.52.5. This enabled automatic detection of beans having the @Component annotation. The <context:component-scan> tag is used to turn this feature on.

For the code example shown in this lesson, we use the lesson14 package from the previous lesson.

<context:component-scan> tag

Right now, we have declared three beans in appContext.xml. Suppose we want to declare the ContentBasedFilter and CollaborativeFilter beans using the @Component annotation instead of defining them using the <bean> tag in appContext.xml.

Here’s the ContentBasedFilter class:

@Component
public class ContentBasedFilter implements Filter {
 //..
}

Here’s the CollaborativeFilter class:

@Component
public class CollaborativeFilter implements Filter {
 //..
}

Just annotating the classes with @Component isn’t enough for Spring to detect them as beans. We need to trigger a component scan. In XML context, the <context:component-scan> tag is used to activate component scanning. To be able to use this tag, we will define a new schema and provide a shortcut name for it as context in appContext.xml.

Note: By default, any tag that is used without any namespace (like <bean>) belongs to the default schema as mentioned here .

In the code shown below, line 3 defines the context namespace and lines 6 and 7 provide the schema location of the namespace.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.