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

本文详细介绍了Spring的自动装配与注解配置,包括如何开启组件扫描、使用注解定义Bean以及基于注解的依赖注入。通过创建Maven工程并导入相关依赖,逐步展示了从 Dao、Service 到 Controller 的注解使用,最后通过测试验证了自动装配的正确性。
摘要由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</

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值