Java Spring bean中的builder-arg中的ref有什么用?

use*_*186 5 java spring spring-mvc constructor-injection

我是Spring Bean的新手,所以我没有在Constructor-arg中使用ref。为什么不像在此示例中那样再次使用值,

这是TextEditor.java文件的内容:

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}
Run Code Online (Sandbox Code Playgroud)

以下是另一个依赖类文件SpellChecker.java的内容:

package com.tutorialspoint;

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

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

}
Run Code Online (Sandbox Code Playgroud)

以下是MainApp.java文件的内容:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}
Run Code Online (Sandbox Code Playgroud)

以下是配置文件Beans.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 -->
   <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <constructor-arg ref="spellChecker"/>
   </bean>

   <!-- Definition for spellChecker bean -->
   <bean id="spellChecker" class="com.tutorialspoint.SpellChecker">
   </bean>

</beans>
Run Code Online (Sandbox Code Playgroud)

在这里,为什么不这样做呢?您可以直接使用spellChecker bean,而不是创建bean textEditor并引用另一个对象spellChecker?

在MainApp.java中

TextEditor te = (TextEditor) context.getBean("spellChecker");
Run Code Online (Sandbox Code Playgroud)

如果因为两个对象都在不同的类中而使用它,那么如果两个对象都在同一个类中,那么我们可以取消引用吗?

另外,如果多个对象引用同一个对象,是否有必要为每个类创建一个bean并使用ref引用该对象,或者使用具有scope = prototype的同一个bean?

asg*_*sgs 3

refSpring bean 的属性引用在某处实例化的另一个 Spring bean 。在你的例子中,SpellChecker是一个Spring单例bean,你想将其“注入”到另一个类型为Spring bean TextEditor。之所以ref有用,是因为大多数 bean 都将是 Singleton,除非您希望每个请求、每个会话等都创建它们,默认范围是 Singleton。

另外,如果多个对象引用同一个对象,是否有必要为每个类创建一个 bean 并使用 ref 引用该对象或使用相同的 bean 但范围=原型?

我认为你想说“多个类引用同一个对象”。在这种情况下,您在类中所做的就是声明对该 bean(或对象)的“引用”。然后您将该 bean“注入”到依赖的类(或 bean)。

您可以阅读有关Spring bean 参考的更多信息。