How to enable auto component scanning in spring?
In general, we define all of our spring beans or components with xml based configurations and we inject all dependencies during the
bean declarations. Spring container registers all beans or compenets as defined in the xml based configurations. Spring also allows you to
define your spring beans and components using annotations as well. When you use annotations, spring provides flexibility to auto scan components
and register with spring container. This page shows an example to enable auto component scan in spring.
You can annotate your services or DAOs with on of @Component, @Service, @Repository, or @Controller annotations. The details
about each of these annotations will be covered in the next examples. If you specify the class with one of these annotations, the class is
eligible for auto scan.
package com.java2novice.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.java2novice.dao.InventoryDao;
@Service("j2nInventoryService")
public class J2nInventoryService {
@Autowired
private InventoryDao inventoryDao;
public void testInventoryServce(){
System.out.println("Inside service class, testInventoryServce()");
inventoryDao.printInventoryDaoStatus();
}
}
|
package com.java2novice.dao;
import org.springframework.stereotype.Component;
@Component
public class InventoryDao {
public void printInventoryDaoStatus(){
System.out.println("Inside InventoryDao & status method");
}
}
|
Here is the xml based configuration file, to enable component auto scanning include component-scan tag, and specify base-package.
The base-package value should be package name and will be scanned for the components with in the packages and its sub-packages.
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.java2novice" />
</beans>
|
Spring bean demo class:
package com.java2novice.test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java2novice.service.J2nInventoryService;
public class SpringDemo {
public static void main(String a[]){
String confFile = "applicationContext.xml";
ConfigurableApplicationContext context
= new ClassPathXmlApplicationContext(confFile);
J2nInventoryService inventoryService =
(J2nInventoryService) context.getBean("j2nInventoryService");
inventoryService.testInventoryServce();
}
}
|
|