Spring 基于 Java 的配置 - 如何不用Beans.xml照样描述bean之间的依赖关系

时间:2022-07-22
本文章向大家介绍Spring 基于 Java 的配置 - 如何不用Beans.xml照样描述bean之间的依赖关系,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

看个具体的例子:首先是配置类,该类的作用相当于Spring常规依赖维护里的Beans.xml:

import org.springframework.context.annotation.*;
@Configuration
public class TextEditorConfig {
   @Bean 
   public TextEditor textEditor(){
      return new TextEditor( spellChecker() );
   }
   @Bean 
   public SpellChecker spellChecker(){
      return new SpellChecker( );
   }
}

TextEditor对SpellChecker的依赖,还是通过构造函数注入:

public class TextEditor {
   private SpellChecker spellChecker;
   public TextEditor(SpellChecker spellChecker){
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
   }
   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

MainApp.java:

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext ctx = 
      new AnnotationConfigApplicationContext(TextEditorConfig.class);

      TextEditor te = ctx.getBean(TextEditor.class);

      te.spellCheck();
   }
}

同样,这个TextEditorConfig也是被SpringCGLib动态增强过: