本文共 2520 字,大约阅读时间需要 8 分钟。
在软件开发中,依赖注入是一种强大的设计模式,能够有效提升代码的可维护性和复用性。尤其在Spring框架中,通过容器管理Bean之间的依赖关系,开发者可以更加专注于业务逻辑的实现,而不是繁琐的依赖管理。
在传统的Java程序中,类之间的依赖关系是单向的,通常由调用者负责创建和注入被依赖对象。然而,这种模式会导致类之间的耦合度过高,复杂化和调试困难。在依赖注入(Dependency Injection, DI)模式下,创建被依赖对象的责任被转移到第三方(如Spring容器),通过反转控制(Inversion of Control, IoC)将依赖关系注入到目标对象中。
这一注入方式通过Spring容器将被依赖对象注入目标Bean的属性字段或方法参数中。常见的方式是使用 setter方法,或者在构造函数中注入。
假设有以下两个Bean:
AccountDaoImpl
public class AccountDaoImpl implements AccountDao { @Override public void add() { System.out.println("save account..."); }}
AccountServiceImpl
public class AccountServiceImpl implements AccountService { private AccountDao accountDao; public void setAccountDao(AccountDao accountDao) { this.accountDao = accountDao; } @Override public void addAccount() { this.accountDao.add(); System.out.println("account added!"); }}
在Spring配置文件中,配置这两个Bean的关系:
通过Spring上下文加载Bean:
public class TestDI_1 { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); AccountService accountService = applicationContext.getBean("accountService"); accountService.addAccount(); }}
运行后,控制台将输出:
save account...account added!
这种方法通过在构造函数中注入依赖对象,适用于那些依赖关系明确且在构建时需要明确设置的场景。
改进后的 AccountServiceImpl_2:
public class AccountServiceImpl_2 implements AccountService { private AccountDao accountDao; public AccountServiceImpl_2(AccountDao accountDao) { System.out.println("Inside AccountServiceImpl_2 constructor."); this.accountDao = accountDao; } @Override public void addAccount() { System.out.println("account added again!"); }}
Spring配置文件:
通过Spring上下文加载Bean:
public class TestDI_2 { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml"); AccountService accountService2 = applicationContext.getBean("accountService2"); accountService2.addAccount(); }}
运行后,控制台将输出:
Inside AccountServiceImpl_2 constructor.save account...account added again!
构造注入的优势:
设值注入的优势:
选择哪种方式取决于具体的场景需求。无论建立哪种形式,Spring的依赖注入都是提升代码可维护性的高效方式。
转载地址:http://hjygz.baihongyu.com/