spring基于注解的bean管理

spring注解开发准备

  • 导入jar包

    • 导入基本的jar包spring基于注解的bean管理_第1张图片

    • 导入aop的jar包这里写图片描述

  • 创建配置文件,引入约束

    • 约束:
      
      <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 http://www.springframework.org/schema/beans/spring-beans.xsd
              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    
    <context:component-scan base-package="com.td">context:component-scan>
    
beans>

使用注解创建对象

  • 使用注解创建对象实例:
    • 在创建对象的类上面使用注解实现spring基于注解的bean管理_第2张图片
    • 测试 代码:spring基于注解的bean管理_第3张图片
  • 创建对象的四个注解,为了在后续的spring版本中对其进行增强
    • @Controller :web层
    • @Service: 业务层
    • @Repository: 持久层
    • @Component
    • ==这四个注解的功能是一样的,都是用来创建对象==
  • 使用注解配置创建对象是单实例还是多实例
    • 默认是单实例的
    • 配置多实例:spring基于注解的bean管理_第4张图片
    • 结果:spring基于注解的bean管理_第5张图片

注解注入属性

  • @Autowired :自动注入
    • 写两个类:
      • Userspring基于注解的bean管理_第6张图片
      • UserServicespring基于注解的bean管理_第7张图片
    • 测试结果:spring基于注解的bean管理_第8张图片
  • @Resource(name=”“)
    • userService类:spring基于注解的bean管理_第9张图片
    • 测试结果:spring基于注解的bean管理_第10张图片

配置文件和注解的混合使用

  • 创建对象操作使用配置文件的方式实现spring基于注解的bean管理_第11张图片
  • 注入属性的操作使用注解方式实现spring基于注解的bean管理_第12张图片
  • 测试结果:spring基于注解的bean管理_第13张图片

你可能感兴趣的:(spring)