【Spring学习笔记三】-依赖注入的两种方式

迷南。 2022-07-19 11:59 363阅读 0赞
  1. 依赖注入通常有两种方式:设值注入和构造注入。设值注入,即Spring容器使用属性的setter方法来注入被依赖的实例。构造注入,即Spring容器使用构造器来注入被依赖的实例。
  2. 一、设值注入
  3. 设值注入是指Spring容器使用属性的setter方法来注入被依赖的实例。这种注入方式简单、直观,因而在Spring的依赖注入里大量使用。还是以上一篇博客中讲到的人和斧子为例。
  4. 首先,定义人和斧子接口。
  5. public interface Person {
  6. //定义一个使用斧子的方法
  7. public void useAxe();
  8. }
  9. public interface Axe {
  10. public String chop();
  11. }
  12. 下面是Person实现类的代码:
  13. public class Chinese implements Person {
  14. private Axe axe;
  15. public void setAxe(Axe axe) {
  16. this.axe = axe;
  17. }
  18. public void ueAxe() {
  19. System.out.println(axe.chop());
  20. }
  21. }
  22. 下面是Axe的实现类
  23. public class StoneAxe implements Axe {
  24. public String chop() {
  25. return “石斧砍柴好慢”;
  26. }
  27. }
  28. bean配置文件如下:
  29. <?xml version="1.0" encoding="UTF-8"?>
  30. <beans xmlns="http://www.springframework.org/schema/beans"
  31. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  32. xsi:schemaLocation="http://www.springframework.org/schema/beans
  33. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  34. <bean id="Chinese" class="com.ceshi.service.impl.Chinese">
  35. <property name="axe" ref="stoneAxe"/>
  36. </bean>
  37. <bean id="stoneAxe" class="com.ceshi.service.impl.StoneAxe">
  38. </bean>
  39. </beans>
  40. 下面是主程序的清单:
  41. public class BeanTest {
  42. public static void main (String [] args) throws Exception {
  43. ApplicationContext ctx = new ClassPathXmlApplicationContext(“bean.xml”);
  44. Person p = ctx.getBean(“Chinese”,Person.class);
  45. p.useAxe();
  46. }
  47. }
  48. 代码运行后,输出:石斧砍柴好慢。
  49. 主程序调用PersonuseAxe方法来执行,该方法的方法体内需要使用Axe实例,但程序没有任何地方将特定的Person实例和Axe实例耦合在一起。Person实例不仅不需要了解Axe实例的具体实现,甚至无须了解Axe的创建过程。
  50. 二、构造注入
  51. 构造注入,即Spring容器使用构造器来注入被依赖的实例。还以上面的实例为例,进行简单的修改。
  52. Chinese类做简单的修改:
  53. public class Chinese implements Person {
  54. private Axe axe;
  55. public Chinese() {
  56. }
  57. //构造注入所需的带参数的构造器
  58. public Chinese(Axe axe) {
  59. this.axe = axe;
  60. }
  61. public void ueAxe() {
  62. System.out.println(axe.chop());
  63. }
  64. }
  65. 之后,还需要对配置文件进行简单修改。如下:
  66. <?xml version="1.0" encoding="UTF-8"?>
  67. <beans xmlns="http://www.springframework.org/schema/beans"
  68. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  69. xsi:schemaLocation="http://www.springframework.org/schema/beans
  70. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  71. <bean id="Chinese" class="com.ceshi.service.impl.Chinese">
  72. <constructor-arg ref="stoneAxe"/>
  73. </bean>
  74. <bean id="stoneAxe" class="com.ceshi.service.impl.StoneAxe">
  75. </bean>
  76. </beans>
  77. 执行结果与设值注入执行结果是一致的。它们的区别在于:创建Person实例中Axe属性的时机不同-设值注入时先通过无参数的构造器创建一个Bean实例,然后调用对应的setter方法注入依赖关系;而构造注入则直接调用有参数的构造器,当Bean实例创建完成后,已经完成了依赖关系的注入。

发表评论

表情:
评论列表 (有 0 条评论,363人围观)

还没有评论,来说两句吧...

相关阅读