• 使用注解的方式装配Bean


    Java知识点总结:想看的可以从这里进入

    9、用注解装配Bean


    Spring是"约定优于配置"的原则,XML文件配置的方式也是异常繁琐,影响开发的效率,所以在Spring3之后就支持大量使用注解的方式开发,使用注解代替xml配置可简化开发,提高效率。

    什么是注解?注解其实就相当于一个标签,比方说我们在公司中有很多部门,你是后勤部门的就做后勤相关工作,你是开发部门的就去做项目开发,注解就是类似功能。给类添加@Controller注解,那这个类就打上了控制层的标签,就去做控制层相关工作,给你加上@Test就打上测试标签,就去做测试相关工作。所以注解相对于XML的配置,它更加的直观,同时也更加便捷。

    9.1、开启注解支持

    Spring默认不使用注解装配 Bean,需要在配置文件中开启注解扫描路径。

    • 在XML文件中添加 context命名空间和约束的配置文件

        
      
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans 	 http://www.springframework.org/schema/beans/spring-beans.xsd">
      beans>
      
        
      
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"	
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             https://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             https://www.springframework.org/schema/context/spring-context.xsd">
      	
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
    • 注解包的扫描

      
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"	
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             https://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context
             https://www.springframework.org/schema/context/spring-context.xsd">
      	
          
          <context:component-scan base-package="需要扫描的路径"/>
          
          
          <context:component-scan base-package="com.yu.springtest">
              
              <context:exclude-filter type="annotation" expression=""/>
          context:component-scan>
      
          
          <context:component-scan base-package="com.yu.springtest" use-default-filters="false">
              
              <context:include-filter type="annotation" expression=""/>
          context:component-scan>
      beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28

    9.2、注解介绍

    • 实例化Bean对象的注解

      • @Component(“id名可省略”):对类进行实例化,不分层。不配置id名则默认为类名
      • @Controller:用在Controller控制层上,实例化对象
      • @Service:用在service业务层层上实例化对象
      • @Repository:用在dao数据访问层上实例化对象
    • 使用注解注入Bean

      • @Autowired(required=false):用于属性、setter 方法、非 setter 方法及构造函数,表示注入一个对象,默认按照类型进行装配

        • required为false时可以为null,可省略,当同一类有两个以上对象时,配合Qualifier使用
        • 在含参的构造方法中使用,加到参数前(@Autowired Person p)
      • @Primary:配合Autowired使用,当有多个实现类时,在类上加此注解会告诉IoC容器优先注入此类。但是当两个实现类都加上Primary注解时,还是会出错,它只能解决首要性问题,而非选择性问题。

      • @Qualifier(value=“名”):结合Autowired(默认为按类注入)使用,它会变成根据名字依赖注入,可以消除Primary注解的问题

      • @Resource(name=“”):相当于@Autowired+@Qualifier同时使用,默认按名字进行装配(jdk中没有,需要导 javax.annotation-api 或 jakarta.annotation-api依赖)

        
        <dependency>
            <groupId>jakarta.annotationgroupId>
            <artifactId>jakarta.annotation-apiartifactId>
            <version>2.1.1version>
        dependency>
        
        <dependency>
            <groupId>javax.annotationgroupId>
            <artifactId>javax.annotation-apiartifactId>
            <version>1.3.2version>
        dependency>
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
        • 7
        • 8
        • 9
        • 10
        • 11
        • 12
        • 如果指定 name 属性,则按实例名称进行装配

        • 如果指定 type 属性,则按 Bean 类型进行装配

        • 如果都不指定,则先按 Bean 实例名称装配,如果不能匹配,则再按照 Bean 类型进行装配

        Autowired和Resource对比
        1、都是用来进行自动装配的,主要用于属性上
        2、Autowired默认是按ByType方式实现的,不配置required时要求对象必须存在
        3、Resource默认通过ByName,如果没有名字则按照ByType实现,否则就报错
        4、Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。
        5、Resource注解用在属性上、setter方法上。
        
        • 1
        • 2
        • 3
        • 4
        • 5
        • 6
      • @Value:给普通的属性设置值,无法注入对象

        • @Value(“”) 直接给属性赋值
        • @Value(“${key}”) 可以根据键获取.properties配置文件中的值
    • 作用域

      • @Scope:标注对象的作用范围,在bean标签内使用
        • @Scope不写时,默认值为singleton单例模式
        • @Scope(“prototype”) 换为多例模式
    • 初始方法和销毁方法(需要导javax.annotation包或依赖)

      • @PostConstruct:标注 方法为初始化方法
      • @PerDestroy::标注方法为销毁方法

    9.3、注解使用

    • 开启注解的支持,并且开启包的扫描

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
                  http://www.springframework.org/schema/beans/spring-beans.xsd
                  http://www.springframework.org/schema/context
                  https://www.springframework.org/schema/context/spring-context.xsd
                  http://www.springframework.org/schema/tx
                  http://www.springframework.org/schema/tx/spring-tx.xsd">
      
          <!--注解包的扫描-->
          <context:component-scan base-package="扫描的路径"/>
      </beans>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
    • 定义一个基础的类

      使用@Component注解表明是一个普通的组件,使用 @Value(“大黄”)注入普通的属性,@Autowired在构造方法、属性、set方法上注入一个依赖的对象

      @Data
      @AllArgsConstructor
      @NoArgsConstructor
      @Component
      public class Dog {
          @Value("大黄")
          private String name;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      @Data
      @NoArgsConstructor
      @AllArgsConstructor
      //表示为一个基础组件
      @Component
      public class Person {
      	/**
          *  value注解用来注入普通的值
          */
          @Value("张三")
          private String name;
      
          @Value("22")
          private int age;
      
          /**
           * 养了条狗,通过注解 Autowired 注入对象
          */
          @Autowired
          private Dog dog;
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
    • 定义 service 获取

      使用 @service 注解标注此类是一个service类

      // 表示是service层的一个组件
      @Service
      public interface AnnotationTestService {
          Person getPerson();
      }
      
      @Service
      public class AnnotationTestServiceImpl implements AnnotationTestService {
      	/**
           * 通过 @Resource 注入IOC容器管理的类
          */
          @Resource
          private Person person;
          @Override
          public Person getPerson() {
              return person;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
    • 定义一个controller类

      使用 @Controller 标注此类是一个Controller, @Autowired注入一个 service

      image-20230329182009018

    • 在测试类中获取这个Controller进行测试

      image-20230329183019375

  • 相关阅读:
    【PyTorch教程】如何使用PyTorch分布式并行模块DistributedDataParallel(DDP)进行多卡训练
    揭开服务网格~Istio Service Mesh神秘的面纱
    对接建行支付
    产品设计的起点:从企业的角度寻找切入点
    Java版企业电子招标采购系统源码Spring Cloud + Spring Boot +二次开发+ MybatisPlus + Redis
    微信授权登录 | 全过程讲解[官方文档->代码梳理->注意点] uniapp+springboot(附Gitee源码)
    AI论文速读 | TPLLM:基于预训练语言模型的交通预测框架
    软考-防火墙技术与原理
    设计模式原则——里氏替换原则
    MyBatis——【第三章】管理关系映射及spring集成
  • 原文地址:https://blog.csdn.net/yuandfeng/article/details/126803959