博客
关于我
Spring DI依赖注入之 set注入柒种方式,美滋滋 (二)
阅读量:241 次
发布时间:2019-03-01

本文共 2538 字,大约阅读时间需要 8 分钟。

依赖注入(DI)详解

依赖注入简介

依赖注入(Dependency Injection,简称DI)是一种软件设计模式,旨在通过在应用程序运行时动态注入依赖关系,从而提升组件的灵活性和可扩展性。与传统的静态绑定不同,依赖注入允许程序在运行时决定对象的创建和注入顺序,这种方式能够显著提高组件的重用频率。

DI 核心概念

为了更好地理解依赖注入,我们需要明确以下四个关键点:

  • 谁依赖谁:通常是应用程序依赖于IoC容器。
  • 为何需要依赖:应用程序需要IoC容器来获取所需的外部资源。
  • 谁注入谁:IoC容器将所需资源注入到应用程序对象中。
  • 注入内容:包括对象、资源、常量数据等。
  • Spring注入方式

    在Spring框架中,依赖注入主要通过以下方式实现:

  • @Value注入:用于注入简单类型值(如字符串、数字等)。
  • @Autowired注入:用于注入Spring-managed bean。
  • @Qualifier注入:用于指定特定的bean进行注入。
  • @Resource注入:用于注入资源文件(如properties文件)。
  • @Component注入:用于注入组件相关属性。
  • 注入示例

    假设我们有以下POJO类:

    public class Student {    private Address address;    private String[] books;    private List
    hobbs; private Map
    card; private Set
    games; private String wife; private Properties info; // setter方法和getter方法(未列出)}

    在Spring配置文件ApplicationContext.xml中,我们可以通过以下方式注入:

    四大名著
    红楼梦
    西游记
    水浒传
    三国演义
    打篮球
    看电影
    敲代码
    狂街
    CF
    LOL
    COC
    BOB
    20210410
    贺伟

    测试用例

    public class MyTest {    public static void main(String[] args) {        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");        Student student = (Student) context.getBean("student");        System.out.println(student.toString());    }}

    总结

    通过以上配置,我们可以实现对不同类型数据的注入,包括单值、数组、List、Map、Set、Properties以及Null值。这些注入方式在Java EE开发中是常见的技术手段,通过合理配置,可以显著提升代码的可维护性和灵活性。

    转载地址:http://denv.baihongyu.com/

    你可能感兴趣的文章
    Project Euler Problem 12: Highly divisible triangular number
    查看>>
    ProjectEuler 2
    查看>>
    projection介绍及EPSG:4326和EPSG:3857的投射转换
    查看>>
    project打开文件时,显示无法识别此文件格式?
    查看>>
    Prometheus + Grafana on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>
    Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
    查看>>
    Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
    查看>>
    Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
    查看>>
    Prometheus 介绍
    查看>>
    Prometheus 安全配置详解
    查看>>
    prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
    查看>>
    Prometheus 安装部署实战
    查看>>
    prometheus 持久化存储方案
    查看>>
    Prometheus 监控系统企业级实战
    查看>>
    Prometheus 监控系统简介
    查看>>