Spring(三) 使用注解实现自动装配

Spring(三)

使用注解实现自动装配

  • 要使用注解须知

    1. 导入约束

    2. 配置注解支持

      <?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:aop="http://www.springframework.org/schema/aop"
             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
              http://www.springframework.org/schema/aop
              https://www.springframework.org/schema/aop/spring-aop.xsd">
      
          <context:annotation-config/>
      
      </beans>
      

      @Autowired

      直接在属性上使用即可,也可以放到Set方法上面

      使用注解可以省略set方法

      当同一个实体类bean 的ID名较多时,可以配合**@Qualifier(value=“ID”)**

      **@Resource(name = “ID名”)**Java内置的注解自动配置,功能更强大但是不常用

      public class People {
          @Autowired
          private Cat cat;
          @Autowired
          public Dog dog;
          private String name;
      
          public Cat getCat() {
              return cat;
          }
      
          @Autowired
          public void setCat(Cat cat) {
              this.cat = cat;
          }
      
          public Dog getDog() {
              return dog;
          }
          @Autowired
          public void setDog(Dog dog) {
              this.dog = dog;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          @Override
          public String toString() {
              return "People{" +
                      "cat=" + cat +
                      ", dog=" + dog +
                      ", name='" + name + '\'' +
                      '}';
          }
      
      }
      

    小结:

    <?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:aop="http://www.springframework.org/schema/aop"
           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
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <context:annotation-config/>
    
    </beans>
    

    @Autowired与**@Resource(name = “ID名”)**的区别:

    • 都是用来自动装配的,都可以放在属性字段上
    • @Autowired通过by name实现,而且必须要求这个对象存在
    • **@Resource(name = “ID名”)**默认通过By name 实现,如果找不到名字,则通过By Type实现
    1. 衍生的注解

      @Component有几个衍生注解,我们在web开发中,会按照MVC三层架构分层

      • dao[@Repository]

      • servic[@Service]]

      • controller[@Controller]

        这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配bean

    2. 自动装配

      **注解说明:**
      
      @Autowired:自动装配通过类型。名字
      
      ​               如果Autowired不能唯一自动装配上属性,只需要通过@Qualifier(value="ID")
      
      @Nullable:   字段标记了这个注解,说明这个字段可以为null
      
      @Resource:自动装配通过名字。类型
      
      @Component : 组件,放在类上,说明这个类被Spring管理了,就是bean
      
      
      
      
      
    3. 作用域

      @Scope("prototype")
      
    4. 小结:

      • xml与注解:

        • xml更加万能,使用与任何场景!维护简单方便便
        • 注解不是自己累使用不了,微护相对复杂
      • 最佳实践

        • xml用来管理bean

        • 注解只负责完成属性的注入

        • 我们在使用的过程中,只需要注意一个问题:必须让注解生效,将就需要开启注解的支持

          <!--自定要扫描的包,这个包下面的注解就会生效-->
          <context:component-scan base-package="com.tingli"/>
          <context:annotation-config/>
          

      使用Java的方式配置Spring

      我们现在要完全不使用Spring的xml配置了,全权交给Java来做

      JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心功能

      实体类

      @Component//组件
      //@Scope("singleton")
      //@Scope("prototype")
      public class User {
      
              @Value("神")//<property name="name" value="神"/>
              public String name;
      
              public String getName() {
                      return name;
              }
      
              public void setName(String name) {
                      this.name = name;
              }
      
              @Override
              public String toString() {
                      return "User{" +
                              "name='" + name + '\'' +
                              '}';
              }
      }
      

      配置文件

      package com.tingli.Config;
      
      import com.tingli.pojo.User;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.ComponentScan;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.context.annotation.Import;
      
      @Configuration//这个也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
                    //@Configuration代表这是一个配置类,集合我们之前看的beans,xml一样
      @ComponentScan("com.tingli.pojo")
      @Import(shenConfig2.class)
      public class shenConfig {
      
          //注册一个bean,就相当于我们之前写的bean标签
          //这个方法的名字就相当于bean标签中的id属性
          //这个方法的返回值,就相当于bean标签的class属性
          @Bean
          public User getUser(){
              return new User();//就是返回要注入到bean的对象
          }
      }
      

      测试类

      public class test {
          public static void main(String[] args) {
      //        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      //
      //        User user = (User) context.getBean("user");
      //        System.out.println(user.name);
      
              //如果完全使用了配置类方法去做,我们之后能通过AnnotationConfigApplicationContext()上下文来获取容器,通过配置类的class对象加载。
              ApplicationContext con = new AnnotationConfigApplicationContext(shenConfig.class);
              User getUser = (User) con.getBean("user");
              System.out.println(getUser);
          }
      }
      

      这种纯Java的配置方式,在SpringBoot种随处可见

*@Nullable 字段标注了这个注解,说明这个字段可以为空

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值