Skip to main content

Spring 4 - Auto Component scanning example

Spring 4 - Auto Component scanning example


Technologies used:   JDK 1.8.0_121 | Spring 4.3.5.RELEASE | Maven 3.9.9 | Eclipse Mars.2 (4.5.2)
Spring provides four stereotype annotations: @Component@Controller@Service and @Repository for spring-managed components.
The @Controller@Service and @Repository annotations are specializations of the @Component annotation for more specific purpose in presentation, service and data access layer respectively.
In Spring framework, we can enable the auto component scanning by using
  • The <context:component-scan/> element in XML based configuration
  • The @ComponentScan annotation in java based configuration
  • The AnnotationConfigApplicationContext#scan() method

Create Spring Components

Create an EmployeeService bean under com.boraji.tutorial.spring.service package as follows.
EmployeeService.java
package com.boraji.tutorial.spring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boraji.tutorial.spring.dao.EmployeeDao;

@Service
public class EmployeeService {

   @Autowired
   private EmployeeDao employeeDao;
   
   public void doSomething(){
      System.out.println("Inside EmployeeService's doSomething() method.");
      employeeDao.doSomething();
   }
}
Create an EmployeeDao bean under com.boraji.tutorial.spring.dao package as follows.
EmployeeDao.java
package com.boraji.tutorial.spring.dao;

import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDao {

   public void doSomething() {
      System.out.println("Inside EmployeeDao's doSomething() method.");
   }
}

Enable component scanning using the <context:component-scan/> element

To enable auto component scanning in XML based configuration, use the <context:component-scan base-package=""/> element as follows.
Beans.xml
<?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-4.3.xsd">

  <context:component-scan
    base-package="com.boraji.tutorial.spring.service,
                  com.boraji.tutorial.spring.dao" />
</beans>
Run application.
MainApp.java
package com.boraji.tutorial.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.boraji.tutorial.spring.service.EmployeeService;

/**
 * @author imssbora
 */
public class MainApp {
   public static void main(String[] args) {

      @SuppressWarnings("resource")
      ApplicationContext context1 = new ClassPathXmlApplicationContext("Beans.xml");
      EmployeeService service1 = context1.getBean(EmployeeService.class);
      service1.doSomething();

   }
}
Output
Inside EmployeeService's doSomething() method.
Inside EmployeeDao's doSomething() method.

Enable component scanning using the @ComponentScan annotation

To enable auto component scanning in java based configuration, annotate your @Configuration class as follows.
AppConfig.java
package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @author imssbora
 */
@Configuration
@ComponentScan(basePackages = { "com.boraji.tutorial.spring.service",
      "com.boraji.tutorial.spring.dao" })
public class AppConfig {
   
}
Run application.
MainApp.java
package com.boraji.tutorial.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.boraji.tutorial.spring.config.AppConfig;
import com.boraji.tutorial.spring.service.EmployeeService;

/**
 * @author imssbora
 */
public class MainApp {
   public static void main(String[] args) {

      @SuppressWarnings("resource")
      ApplicationContext context2=new AnnotationConfigApplicationContext(AppConfig.class);
      EmployeeService service2 = context2.getBean(EmployeeService.class);
      service2.doSomething();
   }
}
Output
Inside EmployeeService's doSomething() method.
Inside EmployeeDao's doSomething() method.

Enable component scanning using the scan() method of application context

Without using the XML or java based configuration, we can enable component scanning using the AnnotationConfigApplicationContext#scan() method as follows.
MainApp.java
package com.boraji.tutorial.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.boraji.tutorial.spring.service.EmployeeService;

/**
 * @author imssbora
 */
public class MainApp {
   public static void main(String[] args) {

      AnnotationConfigApplicationContext context3 =
            new AnnotationConfigApplicationContext();
      
      context3.scan("com.boraji.tutorial.spring.service");
      context3.scan("com.boraji.tutorial.spring.dao");
      context3.refresh();
      
      EmployeeService service3 = context3.getBean(EmployeeService.class);
      service3.doSomething();
      context3.close();
   }
}
Output
Inside EmployeeService's doSomething() method.
Inside EmployeeDao's doSomething() method.

Comments

Popular posts from this blog

Mockito interview Questions

1.       Question 1. What Is Mockito? Answer : Mockito allows creation of mock object for the purpose of Test Driven Development and Behavior Driven development. Unlike creating actual object, Mockito allows creation of fake object (external dependencies) which allows it to give consistent results to a given invocation. 2.       Question 2. Why Do We Need Mockito? What Are The Advantages? Answer : Mockito differentiates itself from the other testing framework by removing the expectation beforehand. So, by doing this, it reduces the coupling. Most of the testing framework works on the "expect-run-verify". Mockito allows it to make it "run-verify" framework. Mockito also provides annotation which allows to reduce the boilerplate code. 3.       Question 3. Can You Explain A Mockito Framework? Answer : In Mockito, you always check a particular class. The dependency in that class is injected using mock object. So, for example, if you have service class

JAVA Expert Interview Questions Answers 2017

Java Basics ::  Interview Questions and Answers Home  »  Interview Questions  »  Technical Interview  »  Java Basics  » Interview Questions 1.     What is the difference between a constructor and a method? A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator. 2.     What is the purpose of garbage collection in Java, and when is it used? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 3.     Describe synchronization in respect to multithreading. With respect to

Java Example Program to Convert List to Set

import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class ListToSet {  /**   * @author Amarjit Kumar   * @category interview questions   *   * Description: Convert List to set in java with example program   *   */  public static void main(String[] args) {   ArrayList<String> arrList= new ArrayList<>();   arrList.add("Java");   arrList.add("Java");   arrList.add("List to String");   arrList.add("Example Program");   Set<String> strSet = new HashSet<String>(arrList);   System.out.println(strSet);   System.out.println(arrList);  } } /*  * Java program to convert list to set. Convert ArrayList of string to HashSet  * in java example program How to convert List to Set in java Set<String> strSet  * = new HashSet<String>(arrList); HashSet having a constructor which will take  * list as an argument. Lets see how to convert list to Set using java program.