Normally you declare all the beans or components in XML bean configuration file, so that Spring container can detect and register your beans or components. Actually, Spring is able to auto scan, detect and instantiate your beans from pre-defined project package, no more tedious beans declaration in in XML file.

Following is a simple Spring project, including a customer service and dao layer. Let’s explore the different between declare components manually and auto components scanning in Spring.

1. Declares Components Manually

See a normal way to declare a bean in Spring.

Normal bean.

package com.mkyong.customer.dao;

public class CustomerDAO
{
@Override
public String toString() {
return "Hello , This is CustomerDAO";
}
}

DAO layer.

package com.mkyong.customer.services;

import com.mkyong.customer.dao.CustomerDAO;

public class CustomerService
{
CustomerDAO customerDAO; public void setCustomerDAO(CustomerDAO customerDAO) {
this.customerDAO = customerDAO;
} @Override
public String toString() {
return "CustomerService [customerDAO=" + customerDAO + "]";
} }

Bean configuration file (Spring-Customer.xml), a normal bean configuration in Spring.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerService" class="com.mkyong.customer.services.CustomerService">
<property name="customerDAO" ref="customerDAO" />
</bean> <bean id="customerDAO" class="com.mkyong.customer.dao.CustomerDAO" /> </beans>

Run it

package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mkyong.customer.services.CustomerService; public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-Customer.xml"}); CustomerService cust = (CustomerService)context.getBean("customerService");
System.out.println(cust); }
}

output

CustomerService [customerDAO=Hello , This is CustomerDAO]

2. Auto Components Scanning

Now, enable Spring auto component scanning features.

Annotate with @Component to indicate this is class is an auto scan component.

package com.mkyong.customer.dao;

import org.springframework.stereotype.Component;

@Component
public class CustomerDAO
{
@Override
public String toString() {
return "Hello , This is CustomerDAO";
}
}

DAO layer, add @Component to indicate this is an auto scan component also.

package com.mkyong.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import com.mkyong.customer.dao.CustomerDAO; @Component
public class CustomerService
{
@Autowired
CustomerDAO customerDAO; @Override
public String toString() {
return "CustomerService [customerDAO=" + customerDAO + "]";
}
}

Put this “context:component” in bean configuration file, it means, enable auto scanning feature in Spring. The base-package is indicate where are your components stored, Spring will scan this folder and find out the bean (annotated with @Component) and register it in Spring container.

<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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.mkyong.customer" /> </beans>

Run it

package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mkyong.customer.services.CustomerService; public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"Spring-AutoScan.xml"}); CustomerService cust = (CustomerService)context.getBean("customerService");
System.out.println(cust); }
}

output

CustomerService [customerDAO=Hello , This is CustomerDAO]

This is how auto components scanning works in Spring.

Custom auto scan component name

By default, Spring will lower case the first character of the component – from ‘CustomerService’ to ‘customerService’. And you can retrieve this component with name ‘customerService’.

	CustomerService cust = (CustomerService)context.getBean("customerService");

To create a custom name for component, you can put custom name like this :

@Service("AAA")
public class CustomerService
...

Now, you can retrieve it with this name ‘AAA’.

	CustomerService cust = (CustomerService)context.getBean("AAA");

Auto Components Scan Annotation Types

In Spring 2.5, there are 4 types of auto components scan annotation types

  • @Component – Indicates a auto scan component.
  • @Repository – Indicates DAO component in the persistence layer.
  • @Service – Indicates a Service component in the business layer.
  • @Controller – Indicates a controller component in the presentation layer.

So, which one to use? It’s really doesn’t matter. Let see the source code of @Repository,@Service or @Controller.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository { String value() default ""; }

You will noticed that all @Repository,@Service or @Controller are annotated with @Component. So, can we use just @Component for all the components for auto scanning? Yes, you can, and Spring will auto scan all your components with @Component annotated.

It’s working fine, but not a good practice, for readability, you should always declare @Repository,@Service or @Controller for a specified layer to make your code more easier to read, as following :

DAO layer

package com.mkyong.customer.dao;

import org.springframework.stereotype.Repository;

@Repository
public class CustomerDAO
{
@Override
public String toString() {
return "Hello , This is CustomerDAO";
}
}

Service layer

package com.mkyong.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.mkyong.customer.dao.CustomerDAO; @Service
public class CustomerService
{
@Autowired
CustomerDAO customerDAO; @Override
public String toString() {
return "CustomerService [customerDAO=" + customerDAO + "]";
} }

Spring Auto scanning components的更多相关文章

  1. Spring学习(十四)----- Spring Auto Scanning Components —— 自动扫描组件

    一.      Spring Auto Scanning Components —— 自动扫描组件 1.      Declares Components Manually——手动配置componen ...

  2. Spring Filter components in auto scanning

    In this Spring auto component scanning tutorial, you learn about how to make Spring auto scan your c ...

  3. Spring Auto proxy creator example

    In last Spring AOP examples – advice, pointcut and advisor, you have to manually create a proxy bean ...

  4. Spring3系列7- 自动扫描组件或Bean

    Spring3系列7- 自动扫描组件或Bean 一.      Spring Auto Scanning Components —— 自动扫描组件 1.      Declares Component ...

  5. Key Components and Internals of Spring Boot Framework--转

    原文地址:http://www.journaldev.com/7989/key-components-and-internals-of-spring-boot-framework In my prev ...

  6. Spring Boot Reference Guide

    Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch,  ...

  7. Spring boot参考指南

    介绍 转载自:https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details 带目录浏览地址:http://ww ...

  8. 译:Spring框架参考文档之IoC容器(未完成)

    6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...

  9. spring boot 打包方式 spring boot 整合mybaits REST services

    <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugi ...

随机推荐

  1. ASP.NET中如何删除最近打开的项目和文件的记录

    ASP.NTET中总是保留最近打开的项目和文件的记录,甚至是已删除的它也不删.下面介绍几种删除的方法: 第一种:建立一个bat文件,以后双击即可清除,内置代码如下: @echo off@REG Del ...

  2. MySQL中REGEXP正则表达式使用大全

    REGEXP在mysql是用来执行正则表达式的一个函数 像php中的preg之类的函数了,regexp正则函数如果只是简单的查询使用like即可,但复杂的还是需要使用regexp了,下面我们来看看. ...

  3. bzoj1913

    这是一道好题,要求每个三点圆覆盖的点数和 我们可以算四边形的贡献,四边形显然分成两种:凸四边形和凹四边形 显然,凹四边形的覆盖只可能是三个点组成三角形包含另一个点,所以贡献是1 凸四边形,其最小圆覆盖 ...

  4. Ajax的“dataType”乱用的陷阱

    $.doAjax({ url : "areaAction_synchronizeArea.do", data : { 'vrvRangeUrl' : synAreaHTTP ,'v ...

  5. 解决IE6下浮动层固定定位的经典方法

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  6. [经验] - JQuery.Ajax + 跨域 (crossDomain) + POST + JSON + WCF RESTful, 5大陷阱和解决方案

    最近在开发WSS RESTful服务的时候, 碰到了这些个纠结的问题. 在网上查找了半天, 找到n多种解决方案, 但是都是部分的, 要么是没有跨域的情况, 要么是没有post的情况, 要么不是用WCF ...

  7. tomcat启动中提示 - consider increasing the maximum size of the cache

    tomcat启动过程中提示: org.apache.catalina.webresources.Cache.getResource Unable to add the resource at xxx ...

  8. python 资料

    主站: 主页:http://python.org/下载:http://python.org/download/文档:http://python.org/doc/ books: ActivePython ...

  9. hdu1998 bjfu1272奇数阶幻方构造

    这题就是一个sb题,本来很水,硬是说得很含混.奇数阶幻方构造其实有好多方法,这题既不special judge,也不说清楚,以为这样能把水题变成难题似的,简直想骂出题人. /* * Author : ...

  10. 让Apache支持ASP.NET

    Apache是目前广泛使用的一种网络服务器程序,不仅在UNIX/LINUX平台上被大量使用,而且在Windows平台上也有许多站点放弃了IIS 而转向Apache..NET是微软推出的功能强大的开发技 ...