7.Spring--使用注解注入Bean

使用注解的方式注入bean

Spring能够从classPath下自动扫描,实例化具有特定注解的类,Spring提供了使用注解的方式注入bean。首先需要在xml中开启解析注解的支持,因为默认情况下是不支持的。
1.引入context命名空间

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

2.在xml中开启注解的支持

  <!-- 使用注解的方式注入bean
        1.同意使用注解
       -->
    <context:annotation-config/>

3.在xml中指定需要扫描的包或者使用java声明
** 3.1使用xml声明**

<context:component-scan base-package="com.crazyorange.springtest.anntationbean,
      com.crazyorange.springtest.autobean"/>

该注解同时还会注册一个AutowireAnnotationBeanPostProcessor实例,该实例会自动装配被@AutoWired,@Resource,@Inject注解标注的对象

3.2使用java代码声明
给一个类标注上@ComponentScan注解,这个注解能够在spring中启用注解扫描的方法,如果没有其他配置的话,默认会扫描和被标注该注解的类同一个包下的其他类。

Paste_Image.png

同时可以通过basePackages指定扫描哪些包

@ComponentScan(basePackageClasses = {ComponentTest.class})

使用component注解

标识了一个类作为一个组件受spring容器管理,并且告诉spring组件要为这个类创建一个bean,没有必要在xml中显示的配置被标记的类的bean了。
component中的参数表示该bean对应的唯一id

Paste_Image.png

使用Required注解

1.Required用来标注setBean属性的方法(。例如:setName,setCar),一旦在set方法上配置了该注解,那么spring的配置xml文件中一定要声明该属性,否则会报错

Paste_Image.png

2.在xml中对属性进行声明

Paste_Image.png

使用Autowired注解

1.该注解可以放在字段,方法,构造器,一切具有参数的方法都可以被注解。默认情况下使用@AutoWired注解注释的属性都用被配置(被spring容器管理)
1.1ControlTest被controller注解标注,被spring容器管理

Paste_Image.png

1.2 ControlTest被AutoWired注解标注,spring容器会自动为它寻找合适的bean创建
Paste_Image.png

2.允许该对象不被注入
AutoWired(required=false)表示允许容器找不到该bean,如果容器找不到对象,不会抛出异常。

Paste_Image.png

2.1当容器中有多个符合条件的注解时,使用@Qualifier注解标识使用哪一个bean,注意@Qualifier中参数为类的名字

Paste_Image.png
Paste_Image.png
Paste_Image.png

泛型注入

Spring可以为子类自动注入子类对应的泛型类型。在子类中调用check方法,会发现对象是UserReporstory


Paste_Image.png
Paste_Image.png
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容