Spring--自动装配

叁歲伎倆 2024-02-18 15:07 92阅读 0赞

一、autoWire:

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

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

二、注解式

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

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

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

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

需要在中配置 :

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

并配置:

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

3)@Component装配:

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

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

并在类中声明:

  1. @Component // Spring will see this and treat @Service in the same way as @Component
  2. public @interface Service {
  3. // ....
  4. }

默认情况下名字为类名改成小写字母。可以指定特定名字,然后可以通过@Resource自动装配值。

发表评论

表情:
评论列表 (有 0 条评论,92人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring自动装配

    自动装配 Spring利用依赖注入(DI),完成对IOC容器中中各个组件的依赖关系赋值 1)、@Autowired:自动注入 默认优先按照类型去容器中找对应