文章标题

来源:互联网 发布:局部搜索算法历史 编辑:程序博客网 时间:2024/06/05 20:43

spring 自动配置和装配

运用注解@

 -在配置Bean文件中,运用@注解即可  <context:component-scan base-package="com.shiyanlou.spring" />

其中 >com.shiyanlou.spring为上级路径的名字,也就是包名,
同时在bean的配置文件中必须用 xmlns来进行声明 context>
* 而context 为ioc实例*

在BEAN文件中的配置

<?xml version="1.0" encoding="UTF-8"?><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/context            http://www.springframework.org/schema/context/spring-context.xsd        http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans.xsd"> <context:component-scan base-package="com.shiyanlou.spring" /></beans>

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

自定义扫描组件名称

                    @Service("AAA")                    public class CustomerService                 需要调用 import包                        import org.springframework.stereotype.Service;

这是第二种方法, 自定义方法

        getbean(“AAA")        这是在getbean时使用自定义扫描组件的方法

自动扫描组件的注释类型

@Component ——表示一个自动扫描 component@Repository ——表示持久化层的 DAO component@Service ——表示业务逻辑层的 Service component@Controller ——表示表示层的 Controller component

自动扫描中过滤组件

#

注意:项目中 autowire 结合 dependency-check 一起使用是一种很好的方法,这样能够确保属性总是可以成功注入。如下:

<bean id="customerService" class="com.shiyanlou.spring.services.CustomerService" autowire="autodetect" dependency-check="objects"> </bean> <bean id="customerDAO" class="com.shiyanlou.spring.dao.CustomerDAO" />