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. HDFS小文件处理——Mapper处理

    处理小文件的时候,可以通过org.apache.hadoop.io.SequenceFile.Writer类将所有文件写出到一个seq文件中. 大致流程如下: 实现代码: package study. ...

  2. lightOJ 1172 Krypton Number System(矩阵+DP)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1172 题意:一个n进制(2<=n<=6)的数字,满足以下条件:(1)至少包 ...

  3. Apache httpd + tomcat 简单集群

    集群其实很简单,我们就来说一下httpd+tomcat集群都要注意哪些部分: 首先使用的东西有 apache-tomcat-8.0.32      下载地址: http://tomcat.apache ...

  4. TUXEDO错误解决方案

    错误1: root@tfjus:/opt/tuxedo/simpapp# buildclient -f simpcl.c -o simpcl simpcl.c: In function 'main': ...

  5. Difference between 2>&-, 2>/dev/null, |&, &>/dev/null and >/dev/null 2>&1

    Reference link: http://unix.stackexchange.com/questions/70963/difference-between-2-2-dev-null-dev-nu ...

  6. 4010: [HNOI2015]菜肴制作

    拓扑排序+堆. 转自popoqqq神犇. 反向建图跑拓扑排序然后逆序输出. 为什么不能正的来呢,因为不知道选当前菜要先制作哪种菜. 逆序过来跑拓扑的话,也能保证满足限制条件编号小的在前面. 题外话:我 ...

  7. POJ 3211 (分组01背包) Washing Clothes

    题意: 小明有一个贤妻良母型的女朋友,他们两个一起洗衣服. 有M种颜色的N件衣服,要求洗完一种颜色的衣服才能洗另外一种颜色. 两人可以同时洗,一件衣服只能被一个人洗. 给出洗每件衣服所用的时间,求两个 ...

  8. 安装IIS之后运行aspx 显示“服务器应用程序不可用” 解决办法

    引起这个的原因大概是现安装了.Net Framework,后装的IIS导致.Net没有在IIS里注册.  另外,还有可能是ASPNET账户没有IIS所指定服务器目录的权限.在资源管理器中找到“工具-文 ...

  9. Servlet,JDBC,JSONObject三者配和处理客户端请求并返回正确的json数据

    JSON简介 首先我们来理解json(JavaScript Object Notation),如果你熟悉python的字典结构和列表结构,其实json格式是非常容易理解的,当然不熟也不难理解,网上的资 ...

  10. ActionBarSherlock的学习笔记(一) -------------- ActionBarSherlock的简要介绍

    1. 介绍 ActionBarSherlock 是Android compatibility library 的一个扩展, 不知道什么原因 Android 兼容开发包没有包含ActionBar. 所以 ...