Spring依赖注入的三种方式小结
发布时间 - 2026-01-11 02:49:05 点击率:次Spring的主要特性包括IOC和DI,其中DI是IOC的基础。在以前的Spring使用过程中大部分都是使用XML配置文件显式配置spring组件,导致大量的XML配置文件以及冗余的XML配置代码。阅读《Spring in Action》后总结Spring的DI功能的三种主要装配方式以及混合装配方式

根据注解自动装配
Spring中有非常丰富的注解,通过这些注解可以方便地配置Spring容器,使得Spring容器可以自动识别相关Bean并做自动注入装配。
使用注解
- @Component注解:标注一个类,标识此类为一个Java Bean。
- @Configuration注解:标注一个类,标识此类为一个Java配置类
- @ComponentScan注解:标注一个类,用以配置扫描的包名称
示例代码
这里使用一个最简单的例子来展示自动装配的配置,代码结构如图所示。
ActionConfig类用于做全局配置,我们知道,一名骑士一般都会有一匹马,所以这里Horse和Knight类作为Java Bean被Spring容器创建,并将Horse类的一个bean注入到Knight中。所以在Horse和Knight中必须使用@Component注解进行修饰。
Knight代码:
package entities;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Component
public class Knight {
private Horse horse;
Knight(Horse horse){
this.horse = horse;
}
public void ride(){
horse.bark();
}
}
Horse代码:
package entities;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Component
public class Horse {
void bark(){
System.out.println("Horse!!!!");
}
}
ActionConfig代码:
package config;
import entities.Knight;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Configuration
@ComponentScan(basePackageClasses = {Knight.class})
public class ActionConfig {
}
这里的ComponentScan注解内的属性用以注明Knight类所在的包为扫描的基础包。凡是这个基础包及其子包内的标注了@Component的类都将被视为Java Bean,这些Bean被Spring容器创建和管理。
Java配置类装配
从自动装配的代码中,可以看出自动装配是非常简单方便的。Java配置类进行装配的方式是采用对配置类中的方法进行注解标注,实现bean的创建和管理。
还是采用以上的例子,现在我们将上面的自动装配改成Java配置类进行装配。
首先,删掉Knight和Horse中的@Component注解,删掉ActionConfig中的@ComponentScn注解,因为这些注解都是自动装配才需要的。
package entities;
/**
* Created by Administrator on 2017/8/3 0003.
*/
public class Knight {
private Horse horse;
public Knight(Horse horse){
this.horse = horse;
}
public void ride(){
horse.bark();
}
}
package entities;
/**
* Created by Administrator on 2017/8/3 0003.
*/
public class Horse {
void bark(){
System.out.println("Horse!!!!");
}
}
ActionConfig类:
package config;
import entities.Horse;
import entities.Knight;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Configuration
public class ActionConfig {
@Bean
public Knight getKnight(){
return new Knight(getHorse());
}
@Bean
public Horse getHorse(){
return new Horse();
}
}
通过@Bean注解对相关的方法进行修饰,Spring就可以知道调用这些方法来构建相应的bean,并注入到依赖的对象中。
XML配置文件装配
使用XML配置文件来装配组件是最为繁琐的,需要对各个bean做一一配置,特别是需要配置构造器或者setter的参数。
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
以上是一个空的XML配置文件,看一下就知道,XML真实复杂啊...
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="knight" class="entities.Knight">
<constructor-arg ref="horse"></constructor-arg>
</bean>
<bean id="horse" class="entities.Horse"></bean>
</beans>
通过配置两个bean元素,并且通过constructor-arg元素来配置构造函数注入的bean,达到依赖注入的目的。
导入和混合配置
有时候单纯的XML配置或者Java配置不满足我们的需求怎么办呢?Spring支持混合配置的方式来管理bean,通过Java和XML配置的混合,达到你想要的效果。
Java配置中引用Java配置
在配置类中使用@Import注解进行引入另一个Java配置类。
package config;
import entities.Horse;
import entities.Knight;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Configuration
@Import(BeautyConfig.class)
public class ActionConfig {
@Bean
public Knight getKnight(){
return new Knight(getHorse());
}
@Bean(name = "horse")
public Horse getHorse(){
return new Horse();
}
}
BeautyConfig代码:
package config;
import entities.Beauty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Created by Administrator on 2017/8/3 0003.
*/
@Configuration
public class BeautyConfig {
@Bean
Beauty getBeauty(){
return new Beauty();
}
}
在Main中,只需要通过ActionConfig就可以获取到所有的上下文对象。
package main;
import config.ActionConfig;
import entities.Beauty;
import entities.Knight;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Created by Administrator on 2017/8/3 0003.
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ActionConfig.class);
Knight knight = context.getBean(Knight.class);
knight.ride();
Beauty beauty = context.getBean(Beauty.class);
beauty.sleep();
}
}
这里简单使用Import引入了另一个配置的Java文件,就实现了将多个bean分别配置到多个Java配置类中。
Java配置中引入XML配置
在Java中引入xml配置的基本方法与引入Java代码配置类似,只需要将@Import改为@ImportResource,配上xml的文件地址即可。
@ImportResource("classpath:spring.xml")
以上,就是Java配置spring依赖注入的方法。
XML配置中引入XML配置
同理,在XML配置中引入XML也需要使用Import,但是在XML中是import标签,通过使用import标签导入另一个xml文件。
这里我新建了一个another.xml的文件,用以作为另一个配置文件示例。在原有的spring.xml中加入以下代码:
<import resource="another.xml"></import>
这样就简单导入了anoter.xml配置文件。
XML配置中引入Java配置
乍看之下,在XML中似乎没有标签可以导入Java配置类的,不过任何Java配置类都是一个bean,所以可以通过配置bean标签来导入Java配置类!
<bean class="config.BeautyConfig"></bean>
通过在XML中配置这个Java配置类的bean,就直接导入了在Java配置类中的所有bean,真是神奇!
以下是配置XML的全部代码:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="another.xml"></import>
<bean class="config.BeautyConfig"></bean>
<bean id="knight" class="entities.Knight">
<constructor-arg ref="horse"></constructor-arg>
</bean>
<bean id="horse" class="entities.Horse"></bean>
</beans>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# Spring依赖注入
# spring三种注入方式
# Spring依赖注入的三种方式实例详解
# Spring依赖注入的两种方式(根据实例详解)
# spring四种依赖注入方式的详细介绍
# 详析Spring中依赖注入的三种方式
# Spring依赖注入(DI)两种方式的示例详解
# 配置文件
# 都是
# 类中
# 多个
# 此类
# 就可以
# 是一个
# 有一
# 一名
# 中有
# 只需
# 可以通过
# 自动识别
# 并将
# 三种
# 都将
# 只需要
# 可以看出
# 要将
# 看一下
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
JS弹性运动实现方法分析
Laravel怎么实现API接口鉴权_Laravel Sanctum令牌生成与请求验证【教程】
Laravel怎么连接多个数据库_Laravel多数据库连接配置
Laravel中的Facade(门面)到底是什么原理
Python自然语言搜索引擎项目教程_倒排索引查询优化案例
5种Android数据存储方式汇总
在centOS 7安装mysql 5.7的详细教程
javascript基本数据类型及类型检测常用方法小结
laravel怎么在请求结束后执行任务(Terminable Middleware)_laravel Terminable Middleware请求结束任务执行方法
Laravel怎么使用Session存储数据_Laravel会话管理与自定义驱动配置【详解】
微博html5版本怎么弄发语音微博_语音录制入口及时长限制操作【教程】
简单实现Android文件上传
如何彻底删除建站之星生成的Banner?
HTML5空格和margin有啥区别_空格与外边距的使用场景【说明】
Laravel如何配置任务调度?(Cron Job示例)
做企业网站制作流程,企业网站制作基本流程有哪些?
为什么php本地部署后css不生效_静态资源加载失败修复技巧【技巧】
原生JS实现图片轮播切换效果
Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】
php 三元运算符实例详细介绍
如何彻底卸载建站之星软件?
如何在橙子建站中快速调整背景颜色?
Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程
微信小程序 闭包写法详细介绍
Laravel Seeder怎么填充数据_Laravel数据库填充器的使用方法与技巧
JavaScript中如何操作剪贴板_ClipboardAPI怎么用
Windows驱动无法加载错误解决方法_驱动签名验证失败处理步骤
如何在万网主机上快速搭建网站?
米侠浏览器网页背景异常怎么办 米侠显示修复
Laravel任务队列怎么用_Laravel Queues异步处理任务提升应用性能
Laravel怎么实现一对多关联查询_Laravel Eloquent模型关系定义与预加载【实战】
JavaScript 输出显示内容(document.write、alert、innerHTML、console.log)
如何在Windows虚拟主机上快速搭建网站?
INTERNET浏览器怎样恢复关闭标签页_INTERNET浏览器标签恢复快捷键与方法【指南】
如何用虚拟主机快速搭建网站?详细步骤解析
制作电商网页,电商供应链怎么做?
Android中Textview和图片同行显示(文字超出用省略号,图片自动靠右边)
Laravel如何实现邮件验证激活账户_Laravel内置MustVerifyEmail接口配置【步骤】
如何快速生成凡客建站的专业级图册?
轻松掌握MySQL函数中的last_insert_id()
音响网站制作视频教程,隆霸音响官方网站?
Laravel API路由如何设计_Laravel构建RESTful API的路由最佳实践
laravel怎么实现图片的压缩和裁剪_laravel图片压缩与裁剪方法
如何在腾讯云免费申请建站?
Laravel Telescope怎么调试_使用Laravel Telescope进行应用监控与调试
Laravel怎么防止CSRF攻击_Laravel CSRF保护中间件原理与实践
清除minerd进程的简单方法
高性能网站服务器部署指南:稳定运行与安全配置优化方案
googleplay官方入口在哪里_Google Play官方商店快速入口指南
Laravel如何处理异常和错误?(Handler示例)

