看个具体的例子:首先是配置类,该类的作用相当于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动态增强过: