spring基于注解的bean管理

本文介绍Spring框架中注解开发的基础知识,包括导入必要的jar包、配置文件的约束定义、如何开启注解扫描以及使用@Controller、@Service等注解创建不同层次的对象。此外,还介绍了如何使用@Autowired和@Resource进行依赖注入,并探讨了配置文件与注解混合使用的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring注解开发准备

  • 导入jar包

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

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

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

    • 约束:
      <?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" 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>
  • 在配置文件中开启注解扫描

<?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" 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"> 

    <!-- 开启 注解扫描 ,扫描com.td包下及子包下的类,方法,属性上的注解-->
    <context:component-scan base-package="com.td"></context:component-scan>
    <!-- 
        开启 注解扫描,只扫描属性上的注解 
    <context:annotation-config></context:annotation-config>
     -->
</beans>

使用注解创建对象

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

注解注入属性

  • @Autowired :自动注入
    • 写两个类:
      • User这里写图片描述
      • UserService这里写图片描述
    • 测试结果:这里写图片描述
  • @Resource(name=”“)
    • userService类:这里写图片描述
    • 测试结果:这里写图片描述

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

  • 创建对象操作使用配置文件的方式实现这里写图片描述
  • 注入属性的操作使用注解方式实现这里写图片描述
  • 测试结果:这里写图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值