Spring--自动装配

来源:互联网 发布:淘宝登录页面一直转圈 编辑:程序博客网 时间:2024/06/15 13:41

一、autoWire:

四种类型:byName、byTpye、default、constructor、no 在<bean>中设置

    <bean id="user" class="com.dw.model.User">      <property name="id" value="1" />      <property name="name" value = "ldw"/>    </bean>    <bean id = "userService" class = "com.dw.service.UserService2" autowire="byName">       <property name="name" value="userService_name"/>    </bean>

二、注解式

1)@Autowired:可以在field或者method上注解,默认是按类型匹配注入

要使该注解有效,需要在xml配置文件中配置:

 <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 


2)@Resource:(默认按名字注入)

需要在<beans>中配置 :

xsi:schemaLocation="http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-2.5.xsd"xmlns:context="http://www.springframework.org/schema/context"

并配置:<context:annotation-config />

@Resource装配顺序
  1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
  3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
  4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

3)@Component装配:

在xml文档中配置:扫描的包,这样配置之后,可以不用在xml文件中写<bean>的相关信息了。

<context:component-scan base-package="org.example"/>

并在类中声明:

@Component // Spring will see this and treat @Service in the same way as @Componentpublic @interface Service {    // ....}
默认情况下名字为类名改成小写字母。可以指定特定名字,然后可以通过@Resource自动装配值。



原创粉丝点击