一、      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
{
@Override
public 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;
} @Override
public 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/beans
http://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
{
@Override
public 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
{
@Autowired
CustomerDAO customerDAO; @Override
public 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/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.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
{
@Override
public 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
{
@Autowired
CustomerDAO customerDAO; @Override
public 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
{
@Override
public 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
{
@Autowired
CustomerDAO customerDAO; @Override
public 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/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.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>

Spring学习(十四)----- Spring Auto Scanning Components —— 自动扫描组件的更多相关文章

  1. Spring学习十四----------Spring AOP实例

    © 版权声明:本文为博主原创文章,转载请注明出处 实例 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4.0 ...

  2. Spring 学习十四 Spring security安全

    Spring security: 我用过的安全机制:   oauth2, filter,  secured方法保护 9.2  保护web请求: 9.2.1  代理Servlet过滤器: Delegat ...

  3. Java开发学习(十四)----Spring整合Mybatis及Junit

    一.Spring整合Mybatis思路分析 1.1 环境准备 步骤1:准备数据库表 Mybatis是来操作数据库表,所以先创建一个数据库及表 create database spring_db cha ...

  4. spring学习 十四 注解AOP 通知传递参数

    我们在对切点进行增强时,不建议对切点进行任何修改,因此不加以使用@PointCut注解打在切点上,尽量只在Advice上打注解(Before,After等),如果要在通知中接受切点的参数,可以使用Jo ...

  5. Spring学习(十九)----- Spring的五种事务配置详解

    前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spring的事务配置虽说也配置过,但是一直没有一个清楚的认识.通过这次的学习发觉Spring的事务配置只要把思路理清,还是比较好掌握的. ...

  6. spring学习 十六 spring加载属性文件

    第一步:创建一个properties文件,以数据库链接作为实例db.properties jdbc.url=jdbc:mysql://192.168.153.128:3306/mybaties?cha ...

  7. Spring学习十五----------Spring AOP API的Pointcut、advice及 ProxyFactoryBean相关内容

    © 版权声明:本文为博主原创文章,转载请注明出处 实例: 1.项目结构 2.pom.xml <project xmlns="http://maven.apache.org/POM/4. ...

  8. spring学习 十八 spring的声明事物

    1.编程式事务: 1.1 由程序员编程事务控制代码.commit与rollback都需要程序员决定在哪里调用,例如jdbc中conn.setAutoCimmit(false),conn.commit( ...

  9. spring学习 十五 spring的自动注入

    一  :在 Spring 配置文件中对象名和 ref=”id” ,id 名相同使用自动注入,可以不配置<property/>,对应的注解@Autowired的作用 二: 两种配置办法 (1 ...

随机推荐

  1. 《编程题》穷举法求N年后有多少头牛

    若一头小母牛,从出生起第四个年头开始每年生一头母牛,按这个规律,第N年时有多少头母牛? #include <iostream> int main(int argc, const char ...

  2. windows实现MySQL主从复制

    MySQL的主从复制是通过binlog日志来实现的,主从复制中的“主”指的是MySQL主服务器上的数据库,“从”指的是MySQL从服务器上的数据库,且这种复制是基于数据库级别的,为此从服务器中的数据库 ...

  3. TortoiseGit bonobo gitserver记住帐号密码

    记住帐号密码有两种方式: 针对服务器存储用户名密码 设置方式为在windows用户存储位置创建文件_netrc,没有后缀名.用文本编辑内容,格式为   machine 115.29.141.162 只 ...

  4. zabbix日常监控项TCP连接状态(六)

    TCP的连接状态对于我们web服务器来说是至关重要的,尤其是并发量ESTAB或者是syn_recv值,假如这个值比较大的话我们可以认为是不是受到了攻击,或是time_wait值比较高的话,我们要考虑看 ...

  5. n=n+1 放在print(s)的上面的影响 (2) n=n=+1在前面,则不满足前面<100条件时候,才跳出while的循环,这时候while循环结束, 到了外面的下一步-->print()

    1+2+3+....+100=     ? n=1 s = 0 while n < =100: s = s+n n= n+1 # n=n+1    在print(s)上面的情况 print(s)

  6. idea插件 总结 自认用比较不错的插件的总结

    1.Background Image Plus 设置你喜欢的图片,提升你编码逼格!还可以设置以轮播图的形式变换图片 还可以设置图片的透明度等现实的方式 2.CodeGlance 类似SublimeTe ...

  7. python的unittest框架中如何删除测试数据,清理环境,可以通过addCleanup函数

    def addCleanup(self, function, *args, **kwargs): """Add a function, with arguments, t ...

  8. 智能指针shared_ptr新特性shared_from_this及weak_ptr

    enable_shared_from_this是一个模板类,定义于头文件<memory>,其原型为: template< class T > class enable_shar ...

  9. httpd:RSA certificate configured for SERVER does NOT include an ID which matches the server name

    这个是因为ssl认证丢失了密钥的问题,Apache的默认配置文件加载了mod_ssl模块,而且指定密钥对儿的位置,就是我测试salt-api时创建密钥对儿的位置.而且还有一个错误就是我密钥对儿指定的h ...

  10. lombok问题

    今天研究了下以dubbo作为分布式的开源项目dubbo-app. 为了排除一些依赖的冲突和干扰,我另外开辟一个新的工作空间,同时我也将公司项目的依赖打个压缩包分类备份下. 这样一来,dubbo-app ...