Spring 自动注入

it2022-05-05  167

1.在 Spring 配置文件中(使用注解时无效)对象名和 ref=”id”id 名相同使用自动注入,可以 不配置<property/>

2.两种配置办法

    2.1 在<bean>中通过 autowire=”” 配置,只对这个<bean>生效

    2.2 在中<beans>(根目录)中通过 default-autowire=””配置,表当当前文件中所 有都是全局配置内容

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd" default-autowire="byName" >

3.autowire=”” 可取值

    3.1 default: 默认值,根据全局 default-autowire=””值.默认全局和局部都没有配置情况下,相当于 no

    3.2 no: 不自动注入

    3.3 byName: 通过名称自动注入.在 Spring 容器中找类的 Id

    3.4 byType: 根据类型注入.

        3.4.1 spring 容器中不可以出现两个相同类型的<bean>,否则会报错

    3.5 constructor: 根据构造方法注入.

        3.5.1 提供对应参数的构造方法(构造方法参数中包含注入对应的那个)

        3.5.2 底层使用 byName, 构造方法参数名和其他<bean>的 id 相同.

 


最新回复(0)