好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring注解实现Bean自动装配示例详解

何为自动装配

自动装配是 Spring 满足 bean 依赖的一种方式。

在使用 Spring 配置 bean 时,我们都要给配置的 bean 的属性设置一个值,如果不手动设置则都是空。而自动的好处就在于,我们不用手动去设置一个值,spring 会在上下文中自动寻找并装配合适的值。

本文主要介绍了Spring注解Bean自动装配的相关内容,下面话不多少了,来一起看看详细的介绍吧

使用须知:

1.导入约束:context约束

2.配置注解的支持: context:annotation-config/

?

1

2

3

4

5

6

7

8

9

10

11

12

<? xml version = "1.0" encoding = "UTF-8" ?>

< beans xmlns = "http://HdhCmsTestspringframework.org/schema/beans"

  xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

  xmlns:context = "http://HdhCmsTestspringframework.org/schema/context"

  xsi:schemaLocation="http://HdhCmsTestspringframework.org/schema/beans

   https://HdhCmsTestspringframework.org/schema/beans/spring-beans.xsd

   http://HdhCmsTestspringframework.org/schema/context

   https://HdhCmsTestspringframework.org/schema/context/spring-context.xsd">

 

  < context:annotation-config />

 

</ beans >

@Autowired

? 通过ByType的方式实现自动装配,且必须要求该对象存在。

? 直接在属性上使用,也可以在set方法上使用。

? 使用Autowired时,可以不用编写set方法,前提是你这个自动装配的属性在IOC容器中存在,且符合Byname方式

?

1

2

@Autowired

private Cat cat;

@Qualifier

?

1

2

3

@Autowired

@Qualifier (value = "dog111" )

private Dog dog;

? 如果@Autowired自动装配的环境比较复杂,可以使用@Qualifier来辅助@Autowired完成自动装配,

? 通过@Qualifier(value = [dog111])指定Bean的ID来装配。

总结

到此这篇关于Spring注解实现Bean自动装配的文章就介绍到这了,更多相关Spring注解Bean自动装配内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/XIaoyummm/article/details/114735415

查看更多关于Spring注解实现Bean自动装配示例详解的详细内容...

  阅读:15次