【问题标题】:Dependency Injection in Spring?Spring中的依赖注入?
【发布时间】:2015-10-04 05:29:34
【问题描述】:

当同时定义了构造函数和setter方法时,我们如何知道spring框架是使用基于构造函数的依赖注入还是基于setter方法的依赖注入

例如..我有两个java类如下.. 文本编辑器.java

public class TextEditor {
    private SpellChecker spellChecker;

    TextEditor(SpellChecker spellChecker){

       this.spellChecker = spellChecker;
    }


    public void setSpellChecker(SpellChecker spellChecker) {

      this.spellChecker = spellChecker;
    }

   // a getter method to return spellChecker
    public SpellChecker getSpellChecker() {
      return spellChecker;
    }

    public void spellCheck() {
      spellChecker.checkSpelling();
    }
}

和 SpellChecker.java

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

在配置文件中,pom.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- Definition for textEditor bean using inner bean -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <property name="spellChecker">
         <bean id="spellChecker" class="SpellChecker"/>
       </property>
   </bean>

</beans>

现在,我们怎么知道spring是使用Constructor或者Setter方法添加了依赖呢?

【问题讨论】:

  • @Autowired@Inject 注释在哪里?显示您的代码。
  • 我在询问使用注释。我正在使用基于 XML 文件配置的结构。
  • 我对注释一无所知。就是这样。

标签: spring spring-mvc


【解决方案1】:

当使用&lt;property&gt; 时,spring 通过 setter 注入依赖项。

如果你想通过构造函数注入它,你使用&lt;constructor-arg&gt;

另见:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-collaborators

【讨论】:

    【解决方案2】:

    这完全取决于开发人员选择他/她如何配置 spring 来注入依赖。

    由于每个人都可以写大量关于依赖注入如何工作的文字,你应该看到/阅读以下内容:

    http://www.journaldev.com/2410/spring-dependency-injection-example-with-annotations-and-xml-configuration

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 2018-11-21
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多