【Spring系列】自动注入(装配)

本文介绍了Spring框架中的自动装配和注解装配功能。通过开启组件扫描,Spring能够自动发现并管理带有@Component注解的Bean。在详细步骤中,创建了DAO、Service和Controller层的接口及实现,并利用@Repository、@Service和@Controller注解进行Bean定义。依赖注入通过@Resource注解实现,减少了XML配置文件的需求。最后,通过测试类验证了自动装配和依赖注入的正确性。
摘要由CSDN通过智能技术生成

org.springframework

spring-aop

4.3.2.RELEASE

org.springframework

spring-context

4.3.2.RELEASE

org.springframework

spring-context-support

4.3.2.RELEASE

org.springframework

spring-aspects

4.3.2.RELEASE

org.springframework

spring-jdbc

4.3.2.RELEASE

2. 开启组件扫描

Spring 默认不使用注解装配 Bean,因此我们需要在 Spring 的 XML 配置中,通过 <context:component-scan> 元素开启 Spring Beans的自动扫描功能。开启此功能后,Spring 会自动从扫描指定的包(base-package 属性设置)及其子包下的所有类,如果类上使用了 @Component 注解,就将该类装配到容器中。

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

<context:component-scan base-package=“com.liu”/>

注意:在使用 context:component-scan 元素开启自动扫描功能前,首先需要在 XML 配置的一级标签 中添加 context 相关的约束


3. 使用注解定义 Bean

Spring 提供了以下多个注解,这些注解可以直接标注在 Java 类上,将它们定义成 Spring Bean。

在这里插入图片描述


4. 基于注解方式实现依赖注入

我们可以通过以下注解将定义好 Bean 装配到其它的 Bean 中。

在这里插入图片描述

1.创建maven工程
2.导入相关依赖在pom.xm配置文件中

junit

junit

4.11

test

org.springframework

spring-core

4.3.2.RELEASE

org.springframework

spring-context

4.3.2.RELEASE

org.springframework

spring-context-support

4.3.2.RELEASE

org.springframework

spring-jdbc

4.3.2.RELEASE

org.springframework

spring-aop

4.3.2.RELEASE

org.springframework

spring-beans

4.3.2.RELEASE

org.springframework

spring-expression

4.3.2.R

  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值