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

一、      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>

 

转载于:https://www.cnblogs.com/powerwu/articles/5150329.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring通过扫描指定的包路径来查找bean定义,并将它们注册到应用程序上下文中。Spring使用`@ComponentScan`注解来指定需要扫描的包路径。当使用`@ComponentScan`注解时,Spring扫描所有被`@Component`、`@Service`、`@Repository`和`@Controller`注解的类,并将它们注册为bean。 例如,以下代码演示了如何在Spring中使用`@ComponentScan`注解扫描名为`com.example`的包下的所有bean定义: ```java @Configuration @ComponentScan("com.example") public class AppConfig { // ... } ``` 除了`@ComponentScan`注解外,还可以使用`@Bean`注解手动注册bean,或者使用XML配置文件来定义bean。 ### 回答2: Spring框架通过Bean扫描机制可以自动检测和加载应用程序中的Bean。 Spring会在应用程序的类路径上扫描指定的包或类,寻找被Spring管理的Bean。这个过程通常在应用程序启动时发生,Spring会搜索并加载符合条件的类,并将其注册为Bean定义。Spring框架提供了几种方式来配置Bean的扫描路径。 首先,可以通过使用@ComponentScan注解来开启Bean的自动扫描。在配置类上加上@ComponentScan注解,并指定需要扫描的包路径,Spring框架将会递归地扫描这些包,查找被@Component、@Service、@Repository、@Controller等注解修饰的类,并将其注册为Bean。 其次,可以使用XML配置文件来进行扫描Bean。在配置文件中使用<context:component-scan>元素,并设置base-package属性为需要扫描的包路径,Spring框架会自动扫描该包下所有被标记的类,并加载注册为Bean。 除此之外,还可以使用基于Java的配置方式,通过编写配置类来定义Bean的扫描路径。在配置类上使用@Configuration和@ComponentScan注解,指定需要扫描的包路径,Spring框架会自动搜索并加载满足条件的类。 总之,无论是通过注解还是XML配置文件,Spring框架可以通过不同的方式来扫描Bean,从而实现自动加载和注册。这样可以避免手动配置每个Bean的信息,提高开发效率,使应用程序更加灵活和可扩展。 ### 回答3: Spring框架通过使用不同的机制来扫描和注册bean。 首先,Spring可以通过基于XML的配置文件来扫描bean。在XML配置文件中,我们可以使用`<bean>`元素来定义一个bean,并通过`id`或`name`属性来标识它。通过在`<bean>`元素中配置适当的信息,如类的全限定名、构造函数参数和属性值,Spring可以实例化和管理这些bean。然后,通过在XML配置文件中使用`<context:component-scan>`元素,可以使Spring自动扫描指定路径下的所有带有特定注解的类,并将它们注册为bean。 其次,Spring还可以通过基于注解的方式来扫描bean。通过在类上使用`@Component`注解或其派生注解(如`@Controller`、`@Service`、`@Repository`等),我们可以指示Spring将该类注册为一个bean。同时,通过使用`@Autowired`注解,我们可以将其他依赖的bean自动注入到当前bean中,实现依赖注入的功能。在启动Spring应用程序时,Spring自动扫描指定路径下的所有类,并将被注解标记的类注册为bean。 最后,Spring还支持自定义扫描和注册bean的机制。我们可以实现`BeanDefinitionRegistryPostProcessor`接口来编写自定义的bean扫描器,通过编程方式将类注册为bean。我们可以根据自己的需求定义扫描路径、过滤条件等,实现更加灵活的bean扫描和注册逻辑。 总结起来,Spring可以通过XML配置文件、基于注解的方式以及自定义扫描器等多种机制来扫描和注册bean,从而实现对应用程序中的组件的管理和控制。这些机制使开发人员能够以更加便捷和灵活的方式管理和使用bean。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值