博客
关于我
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/

    你可能感兴趣的文章
    Pinia:$subscribe()的使用场景
    查看>>
    Pinpoint对Kubernetes关键业务模块进行全链路监控
    查看>>
    Pinterest 大规模缓存集群的架构剖析
    查看>>
    pintos project (2) Project 1 Thread -Mission 1 Code
    查看>>
    PinYin4j库的使用
    查看>>
    PIP
    查看>>
    pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
    查看>>
    pip install mysqlclient报错
    查看>>
    pip install 出现报asciii码错误的解决
    查看>>
    pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
    查看>>
    pip 下载慢
    查看>>
    pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
    查看>>
    pip 安装opencv-python卡死
    查看>>
    pip 安装出现异常
    查看>>
    Pip 安装失败:需要 SSL
    查看>>
    Pip 安装挂起
    查看>>
    pip 或 pip3 为 Python 3 安装包?
    查看>>
    pip 文件损坏导致 pip无法使用 报错 ImportError: cannot import name 'main' from 'pip._int
    查看>>
    pip 无法从 requirements.txt 安装软件包
    查看>>
    pip/pip3更换国内源
    查看>>