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的更多相关文章
-
Spring学习(十四)----- Spring Auto Scanning Components —— 自动扫描组件
一. Spring Auto Scanning Components —— 自动扫描组件 1. Declares Components Manually——手动配置componen ...
-
Spring Filter components in auto scanning
In this Spring auto component scanning tutorial, you learn about how to make Spring auto scan your c ...
-
Spring Auto proxy creator example
In last Spring AOP examples – advice, pointcut and advisor, you have to manually create a proxy bean ...
-
Spring3系列7- 自动扫描组件或Bean
Spring3系列7- 自动扫描组件或Bean 一. Spring Auto Scanning Components —— 自动扫描组件 1. Declares Component ...
-
Key Components and Internals of Spring Boot Framework--转
原文地址:http://www.journaldev.com/7989/key-components-and-internals-of-spring-boot-framework In my prev ...
-
Spring Boot Reference Guide
Spring Boot Reference Guide Authors Phillip Webb, Dave Syer, Josh Long, Stéphane Nicoll, Rob Winch, ...
-
Spring boot参考指南
介绍 转载自:https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details 带目录浏览地址:http://ww ...
-
译:Spring框架参考文档之IoC容器(未完成)
6. IoC容器 6.1 Spring IoC容器和bean介绍 这一章节介绍了Spring框架的控制反转(IoC)实现的原理.IoC也被称作依赖注入(DI).It is a process wher ...
-
spring boot 打包方式 spring boot 整合mybaits REST services
<build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugi ...
随机推荐
-
my97DatePicker日期控件——日期输入框联动,使用focus使第二个输入框没展示出日期控件
描述问题场景: 1.jquery使用的版本是jquery-1.7.2.min.js 2.代码不是写在页面上的,是通过事件后追加的 <!DOCTYPE html> <html> ...
-
Java_ToolKit用法
转自:http://blog.sina.com.cn/s/blog_9e4556250100z5kv.html 此类是所有 Abstract Window Toolkit 实际实现的抽象超类.Tool ...
-
WinForm应用程序之注册模块的设计与实现
Posted on 2012-11-13 10:21 星星之火116 阅读(3260) 评论(4) 编辑 收藏 我们在安装一些桌面应用程序的时候,往往在会有提示当前用户使用的是试用版,要进行注册.刚好 ...
-
MVC 菜鸟学习记录2
自定义Html.Helper扩展方法 在Models文件夹下新建一个静态类,取名为:MyHtmlHelper.cs 将MyHtmlHelper设置为static,并写入以下的一个静态方法 public ...
-
【网络流24题】No.8 机器人路径规划问题
[题意] 机器人 Rob 可在一个树状路径上*移动. 给定树状路径 T 上的起点 s 和终点 t, 机器人 Rob 要从 s 运动到 t. 树状路径 T 上有若干可移动的障碍物. 由于路径狭窄, 任 ...
-
c# 获取客户端ip
针对 HttpContext.Current.Request.UserHostAddress 如果客户使用的是代理,将获取不到真是的ip 要想透过代理服务器取得客户端的真实IP地址,就要使用 Requ ...
-
Java容器源码解析之——ArrayList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess ...
-
使用GetThumbnailImage进行图片缩放操作
/// <summary> /// 获取等比例缩放图片的方法 /// </summary> /// <param name=&q ...
-
C#之IComparable用法,实现List<;T>;.sort()排序
这篇文章主要介绍了C#的一些基础知识,主要是IComparable用法,实现List<T>.sort()排序,非常的实用,这里推荐给大家. List<T>.sort()可以 ...
-
BZOJ_3697_采药人的路径_点分治
BZOJ_3697_采药人的路径_点分治 Description 采药人的药田是一个树状结构,每条路径上都种植着同种药材. 采药人以自己对药材独到的见解,对每种药材进行了分类.大致分为两类,一种是阴性 ...