Monday, November 18, 2024
Google search engine
HomeLanguagesJavaSpring @ComponentScan Annotation with Example

Spring @ComponentScan Annotation with Example

Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation.

Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. 

One of the most important annotations in spring is @ComponentScan which is used along with the @Configuration annotation to specify the packages that we want to be scanned. @ComponentScan without arguments tells Spring to scan the current package and all of its sub-packages.  So let’s understand @ComponentScan Annotation with an example project.

Implementation: Suppose we have already a Java project and all the Spring JAR files are imported into that project. Now let’s create a simple class named College and inside the class, we have a simple method. 

A. File: College.java

Java




// Java Program to Illustrate College Class
 
package ComponentAnnotation;
 
// Class
public class College {
 
    // Method
    public void test()
    {
 
        // Print statement whenever this method of
        // College class is called
        System.out.println("Test College Method");
    }
}


Now let’s create a Bean for this class inside the beans.xml file. Below is the code for the beans.xml file.

B. File: beans.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 
    <bean id="collegeBean" class="ComponentAnnotation.College"></bean>
</beans>


 
 

But we don’t want to create the bean by this method. We want to use some annotation for doing this task. So we can use @Component annotation for doing the same task. So we can modify our College.java file something like this.

C. File: Modified College.java 

Java




// Java Program to Illustrate Component Annotation
// Indulgence in College Class
 
package ComponentAnnotation;
 
// Importing required classes
import org.springframework.stereotype.Component;
 
// Annotation
@Component("collegeBean")
 
// Class
public class College {
 
    // Method
    public void test()
    {
        // Print statement whenever this method is called
        System.out.println("Test College Method");
    }
}


 
 

But in this case, we have to write the following line inside the beans.xml file.

<context:component-scan base-package="ComponentAnnotation"/>

Note: But we don’t want to use the complete beans.xml file in our project. So what we can do to replace the beans.xml file? In general, beans.xml is a configuration file. So we can create a configuration class in Java and just make this class our Configuration class by just using the @Configuration Annotation. Yes, we can do that. So now let’s create another class named CollegeConfig. One more thing is, we have to also use the @ComponentScan annotation because we need to scan through all our components. In this particular package “ComponentAnnotation” whatever the classes present, the @Component annotation is going to create the bean for that, and to do that inside the Configuration classes we need to define our base package something like as shown below as follows:

@ComponentScan(basePackages = "ComponentAnnotation")  

So below is the code for the CollegeConfig.java file

D. File: CollegeConfig.java 

Java




// Java Program to Illustrate Configuration of
// College Class
 
package ComponentAnnotation;
 
// Importing required classes
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
// Annotation
@Configuration
@ComponentScan(basePackages = "ComponentAnnotation")
 
// Class
public class CollegeConfig {
}


Now to check our application let’s create a main method inside our Main class. Below is the code for the Main.java file. Comments are added inside the code to understand the code in more detail.

E. Application or Main File: Main.java

Example

Java




// Java Program to Illustrate Application Class
 
package ComponentAnnotation;
 
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 
// Main class
public class Main {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Using AnnotationConfigApplicationContext
        // instead of ClassPathXmlApplicationContext
        // Because we are not using XML Configuration
        ApplicationContext context
            = new AnnotationConfigApplicationContext(
                CollegeConfig.class);
 
        // Get the bean and storing it in
        // a object of College class type
        College college
            = context.getBean("collegeBean", College.class);
 
        // Invoking the method
        // inside main() method
        college.test();
    }
}


Output:

Test College Method 

RELATED ARTICLES

Most Popular

Recent Comments