📜  春季-注入内豆

📅  最后修改于: 2020-11-11 07:01:56             🧑  作者: Mango


如您所知,Java内部类是在其他类的范围内定义的,类似地,内部Bean是在另一个bean的范围内定义的Bean。因此,元素内的元素称为内部bean,如下所示。





   
      
         
      
   


让我们准备好运行中的Eclipse IDE,并按照以下步骤创建Spring应用程序:

Steps Description
1 Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.
2 Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3 Create Java classes TextEditor, SpellChecker and MainApp under the com.tutorialspoint package.
4 Create Beans configuration file Beans.xml under the src folder.
5 The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

这是TextEditor.java文件的内容-

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;
   
   // a setter method to inject the dependency.
   public void setSpellChecker(SpellChecker spellChecker) {
      System.out.println("Inside setSpellChecker." );
      this.spellChecker = spellChecker;
   }
   
   // a getter method to return spellChecker
   public SpellChecker getSpellChecker() {
      return spellChecker;
   }
   public void spellCheck() {
      spellChecker.checkSpelling();
   }
}

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

package com.tutorialspoint;

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

以下是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();
   }
}

以下是配置文件Beans.xml ,该文件具有用于基于setter的注入的配置,但使用内部bean-





   
   
      
         
      
   


完成创建源和Bean配置文件后,让我们运行该应用程序。如果您的应用程序一切正常,它将打印以下消息:

Inside SpellChecker constructor.
Inside setSpellChecker.
Inside checkSpelling.