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

原文地址


http://www.cnblogs.com/leiOOlei/p/3547589.html


一、      Spring Auto Scanning Components —— 自动扫描组件    

    1.      Declares Components Manually——手动配置component

    2.      Auto Components Scanning——自动扫描组件

    3.      Custom auto scan component name——自定义扫描组件名称

    4.      Auto Components Scan Antotation Types——自动扫描组件的注释类型

二、      Spring Filter Components In Auto Scanning —— 在自动扫描中过滤组件

    1.      Filter Component——include

    2.      Filter Component——exclude

 

 

一、      Spring Auto Scanning Components —— 自动扫描组件

通常你可以在xml配置文件中,声明一个bean或者component,然后Spring容器会检查和注册你的bean或component。实际上,Spring支持自动扫描bean或component,你可以不必再在xml文件中繁琐的声明bean,Spring会自动扫描、检查你指定包的bean或component。

以下列举一个简单的Spring Project,包含了Customer、Service、DAO层,让我们来看一下手动配置和自动扫描的不同。

1.      Declares Components Manually——手动配置component

先看一下正常手动配置一个bean

DAO层,CustomerDAO.java如下:

复制代码
package com.lei.customer.dao;public class CustomerDAO 
{@Overridepublic String toString() {return "Hello , This is CustomerDAO";}    
}
复制代码

 

Service层,CustomerService.java如下:

复制代码
package com.lei.customer.services;import com.lei.customer.dao.CustomerDAO;public class CustomerService 
{CustomerDAO customerDAO;public void setCustomerDAO(CustomerDAO customerDAO) {this.customerDAO = customerDAO;}@Overridepublic String toString() {return "CustomerService [customerDAO=" + customerDAO + "]";}}
复制代码

 

 

配置文件,Spring-Customer.xml文件如下:

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

 

运行如下代码,App.java如下:

复制代码
package com.lei.common;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.lei.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);}
}
复制代码

 

输出结果:CustomerService [customerDAO=Hello , This is CustomerDAO]

 

2.      Auto Components Scanning——自动扫描组件

现在,看一下怎样运用Spring的自动扫描。

用注释@Component来表示这个Class是一个自动扫描组件。

Customer.java如下:

复制代码
package com.lei.customer.dao;import org.springframework.stereotype.Component;@Component
public class CustomerDAO 
{@Overridepublic String toString() {return "Hello , This is CustomerDAO";}    
}
复制代码

 

CustomerService.java如下:

复制代码
package com.lei.customer.services;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;import com.lei.customer.dao.CustomerDAO;@Component
public class CustomerService 
{@AutowiredCustomerDAO customerDAO;@Overridepublic String toString() {return "CustomerService [customerDAO=" + customerDAO + "]";}
}
复制代码

 

 

配置文件Spring-customer.xml如下

 

复制代码
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><context:component-scan base-package="com.lei.customer" /></beans>
复制代码

 

 

 

注意:

以上xml文件中,加入了“context:component-scan”标签,这样就将Spring的自动扫描特性引入,base-package表示你的组件的存放位置,Spring将扫描对应文件夹下的bean(用@Component注释过的),将这些bean注册到容器中。

       最后运行结果与手动配置的结果一致。

3.      Custom auto scan component name——自定义扫描组件名称

上例中,默认情况下,Spring将把组件Class的第一个字母变成小写,来作为自动扫描组件的名称,例如将“CustomerService”转变为“customerservice”,你可以用“customerService”这个名字调用组件,如下:

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

 

你可以像下边这样,创建自定义的组件名称:

 

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

 

现在,可以调用自己定义的组件了,如下:

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

 

4.      Auto Components Scan Antotation Types——自动扫描组件的注释类型

有4种注释类型,分别是:

@Component      ——表示一个自动扫描component

@Repository              ——表示持久化层的DAO component

@Service             ——表示业务逻辑层的Service component

@Controller        ——表示表示层的Controller component

 

以上4种,在应用时,我们应该用哪一种?让我们先看一下@Repository、@Service、@Controller的源代码

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

 

你还可以看一下@Service、@Controller的源代码,发现它们都用@Component注释过了,所以,在项目中,我们可以将所有自动扫描组件都用@Component注释,Spring将会扫描所有用@Component注释过得组件。

       实际上,@Repository、@Service、@Controller三种注释是为了加强代码的阅读性而创造的,你可以在不同的应用层中,用不同的注释,就像下边这样。

DAO层:

复制代码
package com.lei.customer.dao;import org.springframework.stereotype.Repository;@Repository
public class CustomerDAO 
{@Overridepublic String toString() {return "Hello , This is CustomerDAO";}    
}
复制代码

 

 

Service层:

复制代码
package com.lei.customer.services;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.lei.customer.dao.CustomerDAO;@Service
public class CustomerService 
{@AutowiredCustomerDAO customerDAO;@Overridepublic String toString() {return "CustomerService [customerDAO=" + customerDAO + "]";}}
复制代码

 

 

二、      Spring Filter Components In Auto Scanning —— 在自动扫描中过滤组件

1.      Filter Component——include

下例演示了用“filter”自动扫描注册组件,这些组件只要匹配定义的“regex”的命名规则,Clasee前就不需要用@Component进行注释。

DAO层,CustomerDAO.java如下:

复制代码
package com.lei.customer.dao;public class CustomerDAO 
{@Overridepublic String toString() {return "Hello , This is CustomerDAO";}    
}
复制代码

 

Service层,CustomerService.java如下:

复制代码
package com.lei.customer.services;import org.springframework.beans.factory.annotation.Autowired;
import com.lei.customer.dao.CustomerDAO;public class CustomerService 
{@AutowiredCustomerDAO customerDAO;@Overridepublic String toString() {return "CustomerService [customerDAO=" + customerDAO + "]";}}
复制代码

 

Spring Filtering,xml配置如下:

复制代码
<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><context:component-scan base-package="com.lei" ><context:include-filter type="regex" expression="com.lei.customer.dao.*DAO.*" /><context:include-filter type="regex" expression="com.lei.customer.services.*Service.*" /></context:component-scan></beans>
复制代码

 

注意:

以上xml文件中,所有文件名字,只要包含DAO和Service(*DAO.*,*Service.*)关键字的,都将被检查注册到Spring容器中。

 

运行以下代码:

复制代码
package com.lei.common;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import com.lei.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);}
}
复制代码

 

运行结果:CustomerService [customerDAO=Hello , This is CustomerDAO]

 

2.      Filter Component——exclude

你也可以用exclude,制定组件避免被Spring发现并被注册到容器中。

以下配置排除用@Service注释过的组件

<context:component-scan base-package="com.lei.customer" ><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />        
</context:component-scan>

 

以下配置排除包含“DAO”关键字的组件

<context:component-scan base-package="com.lei" ><context:exclude-filter type="regex" expression="com.lei.customer.dao.*DAO.*" />        
</context:component-scan>



转载于:https://www.cnblogs.com/zaifeng0108/p/7225055.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/429415.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

数据插不进mysql_数据插入不进数据库里面去。

1&#xff1a;index.php提交到&#xff1a;index_ok.php2:连接数据库文件&#xff1a;conn.php<?php $idmysql_connect("localhost","root","root")ordie(连接失败:.mysql_error());if(mysql_select_db("db_databas...1&#xff1a;ind…

Android_Kotlin 代码学习

https://github.com/ldm520/Android_Kotlin_Demo转载于:https://www.cnblogs.com/simadi/p/6704864.html

liberty配置mysql数据源_Bluemix Liberty server.xml MySQL数据源配置

如果要连接到mysql数据库并希望 manually 在server.xml中提供凭据&#xff0c;则可以执行以下操作&#xff1a;server.xml中&#xff1a;URL"jdbc:mysql://1.2.3.4:3306/db"password"mypassword" user"admin" />name"MySQL Connector&qu…

CI Weekly #17 | flow.ci 支持 Java 构建以及 Docker/DevOps 实践分享

这周一&#xff0c;我们迫不及待写下了最新的 changelog —— 项目语言新增「Java」。创建 Java 项目工作流和其它语言项目配置很相似&#xff0c;flow.ci 提供了默认的 Java 项目构建流程模版&#xff0c;快去试试吧&#xff5e; 最近 flow.ci 2017 招聘计划正式启动&#xff…

mysql mgr 配置_MySQL5.7 MGR安装配置

MySQL5.7 MGR安装配置一、服务器规划mysql_mgr_01192.168.10.223mysql_mgr_02192.168.10.224mysql_mgr_03192.168.10.225二、配置文件1. mysql_mgr_01[rootmysql_mgr_01 tmp]# cat /etc/my.cnf[mysqld]sql_mode STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_D…

你让我怎么说

小组长分配任务,优化首页列表加载响应时间, 涉及更改一同事代码,遇到某个模型命名不解,UserInfoId和CurrentUserInfoId,问这两个干啥使, 答曰UserInfoId是用户的Id,CurrentUserInfoId不知道谁加的, 不解,问道"你写的方法你不知道?", 答曰,不知.后发现是另外一同事共…

python选取tensor某一维_Pytorch的Tensor操作(1)

类型推断torch.randn()&#xff1a;随机初始化a.type()&#xff1a;返回类型type()&#xff1a;返回基本类型isinstance() &#xff1a;检查类型cuda会影响数据类型标量维度(dimention)为0的标量标量的shape&#xff1a;返回类型为【】(空的list)&#xff0c;返回长度也为0a.di…

201521123014 《Java程序设计》第8周学习总结

201521123014 《Java程序设计》第8周学习总结 1. 本周学习总结 1.1 以你喜欢的方式&#xff08;思维导图或其他&#xff09;归纳总结集合与泛型相关内容。 泛型&#xff08;编写的代码可被不同类型的对象所重用&#xff09; Java中一个集合可以放任何类型的对象&#xff0c;因为…

java remove all_如何使用Java List等集合类的removeAll方法

展开全部List等集合类的removeAll方法&#xff0c;API文档描述如下e69da5e6ba9062616964757a686964616f31333361303062&#xff1a;boolean removeAll(Collection> c)从列表中移除指定 collection 中包含的其所有元素(可选操作)。用法案例如下&#xff1a;List list1 new A…

【4.0】jdbcTemplate

1.什么是jdbcTemplate? 2.使用jdbcTemplate 3.crud操作 参考博文&#xff1a;http://blog.csdn.net/u014800380/article/details/64125653 4.采用配置文件的方式使用jdbcTemplate 参考博文&#xff1a;http://suyanzhu.blog.51cto.com/8050189/1563219/ 参考博文原文&#x…

java 默认排序方式_Java Collections.sort()实现List排序的默认方法和自定义方法

1.java提供的默认list排序方法主要代码&#xff1a;list list new arraylist();list.add("刘媛媛");list.add("王硕");list.add("李明");list.add("刘迪");list.add("刘布");//升序collections.sort(list,collator.getinst…

java random算法_负载均衡--随机算法(Random)

随机算法是指&#xff1a;从服务器列表中&#xff0c;随机选取一台服务器进行访问。由概率论可以得知&#xff0c;随着客户端调用服务端的次数增多&#xff0c;其实际效果趋近于平均分配请求到服务端的每一台服务器&#xff0c;也就是达到轮询的效果。一、算法描述假设有 N 台服…

Mysql group by 问题

根据标准sql规定&#xff0c;select字段&#xff08;除聚合函数与&#xff09;必须跟在group by后&#xff0c;但mysql除外&#xff0c;即select * from table a group by a.property 无报错 聚合函数如下&#xff1a; 1. avg() 取其平均数 2.count() 取其数量,返回值为int 3.…

java io体系_java IO流的体系结构图

常用字节流字符流字节流 InputStream 字符流 ReaderFileInputStream BufferedReaderFilte…

jetty java 禁用目录列表_java – 如何禁用Jetty的WebAppContext目录列表?

我将Jetty(版本7.4.5.v20110725)嵌入到java应用程序中。我使用Jetty的WebAppContext在./webapps/jsp/中提供JSP页面&#xff0c;但是如果我访问localhost&#xff1a;8080 / jsp /我获取了Jetty的目录列表&#xff0c;以获取./webapps/jsp/的所有内容。我已经尝试将dirAllowed参…

Arch Linux 安装总结

这篇随笔的目的&#xff1a; 这篇是我今天重新安装后&#xff0c;觉得每次都看别人的来复制&#xff0c;太麻烦了&#xff0c;每次自己解决的一些问题&#xff0c;又不能及时记录下来&#xff0c;导致每次都又需要一通乱找&#xff0c;肯定比第一次开始搜索的要快&#xff0c;但…

java空心正方形代码_从Java中的用户输入绘制空心星号正方形/矩...

我正在尝试创建一个程序,要求用户提供正方形/矩形的宽度和长度尺寸,然后使用#符号将其绘制出来.我几乎了解了,除了我似乎不太了解矩形的右边以正确打印出来…这是我的代码&#xff1a;import java.util.Scanner;public class warmup3{public static void main(String[] args){i…

2017.4.17------软件测试的艺术+整理以前的摘记

2017.4.17 以下内容来自《软件测试的艺术》 第1页——14页。供自己学习使用。 第一章 软件测试&#xff1a;就是一个过程或一个系列过程&#xff0c;用来确认计算机代码完成了其应该完成的功能&#xff0c;不执行其不该有的操作。 第二章 测试人员需要有正确的态度。每当测试一…

基于MODBUS协议的单片机与(串口屏)触摸屏通信(图文)

基于MODBUS协议的单片机与(串口屏)触摸屏通信(图文) 导读&#xff1a;触摸屏能够直观、生动地显示运行参数和运行状态&#xff0c;而且通过触摸屏画面可以直接修改系统运行参数&#xff0c;人机交互性好。触摸屏和单片机通信&#xff0c;需要根据触摸屏采用的通信协议为单片机编…

java mask_Java 三大属性:

# Java 三大属性&#xff1a;面试时候问的一个很基础的问题&#xff0c;也是面向对象的三大特点。## 一、封装首先&#xff0c;属性可用来描述同一类事物的特征&#xff0c;方法可描述一类事物可做的操作。封装就是把属于同一类事物的共性(包括属性与方法)归到一个类中&#xf…