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 m...

REST Methods

GET ============================================= HTTP GET method is used to **read** (or retrieve) a representation of a resource. According to the design of the HTTP specification, GET requests are used only to read data and not change it. Therefore, when used this way, they are considered safe. That is, they can be called without risk of data modification or corruption. Means calling it once has the same effect as calling it 10 times. Additionally, GET is idempotent which means that making multiple identical requests ends up having the same result as a single request. Donot expose unsafe operations via GET. It should never modify any resources on the server. Example: ------------    GET http://www.example.com/customers/12345/orders POST =================================== -> The POST verb is most-often utilized to **create** new resources. In particular, it's used to create subordinate resources. -> That is, subordinate to some other (e.g. parent) reso...