当前位置:K88软件开发文章中心编程语言JavaSpring → 文章内容

Spring 基于 Java 的配置

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 16:20:56

llChecker){ System.out.println("Inside TextEditor constructor." ); this.spellChecker = 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.annotation.*;public class MainApp { public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(TextEditorConfig.class); TextEditor te = ctx.getBean(TextEditor.class); te.spellCheck(); }}一旦你完成了创建所有的源文件并添加所需的额外的库后,我们就可以运行该应用程序。你应该注意这里不需要配置文件。如果你的应用程序一切都正常,将输出以下信息:Inside SpellChecker constructor.Inside TextEditor constructor.Inside checkSpelling.@Import 注解:@import 注解允许从另一个配置类中加载 @Bean 定义。考虑 ConfigA 类,如下所示:@Configurationpublic class ConfigA { @Bean public A a() { return new A(); }}你可以在另一个 Bean 声明中导入上述 Bean 声明,如下所示:@Configuration@Import(ConfigA.class)public class ConfigB { @Bean public B a() { return new A(); }}现在,当实例化上下文时,不需要同时指定 ConfigA.class 和 ConfigB.class,只有 ConfigB 类需要提供,如下所示:public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class); // now both beans A and B will be available... A a = ctx.getBean(A.class); B b = ctx.getBean(B.class);}生命周期回调@Bean 注解支持指定任意的初始化和销毁的回调方法,就像在 bean 元素中 Spring 的 XML 的初始化方法和销毁方法的属性:public class Foo { public void init() { // initialization logic } public void cleanup() { // destruction logic }}@Configurationpublic class AppConfig { @Bean(initMethod = "init", destroyMethod = "cleanup" ) public Foo foo() { return new Foo(); }}指定 Bean 的范围:默认范围是单实例,但是你可以重写带有 @Scope 注解的该方法,如下所示:@Configurationpublic class AppConfig { @Bean @Scope("prototype") public Foo foo() { return new Foo(); }}

上一页  [1] [2] 


Spring 基于 Java 的配置