Spring学习历程 --- 基于 Java 类的配置

Spring学习历程 --- 基于 Java 类的配置

基于Java配置选项,可以编写大多数的Spring不用配置XML,但有几个基于Java的注释的帮助下解释。

@Configuration & @Bean 注解:

注释类与@Configuration表示这个类可以使用Spring IoC容器为bean定义的来源。在@Bean 注解告诉Spring的注解为@Bean的一个方法将返回应注册为在Spring应用程序上下文中的bean对象。最简单可行的@Configuration类将如下所示: 

package com.yiibai;import org.springframework.context.annotation.*;@ConfigurationpublicclassHelloWorldConfig{@BeanpublicHelloWorld helloWorld(){returnnewHelloWorld();}}

上面的代码将等同于下面的XML配置:

<beans><beanid="helloWorld"class="com.yiibai.HelloWorld"/></beans>

下面注解为@Bean的方法名称作为工作bean的id,它创建并返回实际的bean。配置类可以有声明多个@Bean。一旦配置类定义,可以加载和提供他们使用AnnotationConfigApplicationContext 如下,以Spring容器:

publicstaticvoid main(String[] args){ApplicationContext ctx =newAnnotationConfigApplicationContext(HelloWorldConfig.class);HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();}

可以加载各种配置类别如下:

publicstaticvoid main(String[] args){AnnotationConfigApplicationContext ctx =newAnnotationConfigApplicationContext();

   ctx.register(AppConfig.class,OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();}
例子:

让我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:

1Create a project with a name SpringExample and create a package com.yiibai under the src folder in the created project.
2Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4Create Java classes HelloWorldConfigHelloWorld and MainApp under the com.yiibaipackage.
5The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

这里是HelloWorldConfig.java文件的内容:

package com.yiibai;import org.springframework.context.annotation.*;@ConfigurationpublicclassHelloWorldConfig{@BeanpublicHelloWorld helloWorld(){returnnewHelloWorld();}}

这里是HelloWorld.java的文件的内容:

package com.yiibai;publicclassHelloWorld{privateString message;publicvoid setMessage(String message){this.message  = message;}publicvoid getMessage(){System.out.println("Your Message : "+ message);}}

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

package com.yiibai;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.*;publicclassMainApp{publicstaticvoid main(String[] args){ApplicationContext ctx =newAnnotationConfigApplicationContext(HelloWorldConfig.class);HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

      helloWorld.setMessage("Hello World!");
      helloWorld.getMessage();}}

创建所有的源文件并添加所需的额外(外部)的库,让我们运行应用程序。应该注意,不需要配置文件。如果一切顺利,这将打印以下信息:

Your Message : Hello World!
注入Bean的依赖关系:

当@Bean对彼此的依赖,表达这种依赖很简单,只要有一个Bean的方法调用另一个如下:

package com.yiibai;import org.springframework.context.annotation.*;@ConfigurationpublicclassAppConfig{@BeanpublicFoo foo(){returnnewFoo(bar());}@BeanpublicBar bar(){returnnewBar();}}

在这里,Bean接收基准通过构造函数注入。现在,让我们看到一个正常工作的例子:

例子:

让我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:

1Create a project with a name SpringExample and create a package com.yiibai under the src folder in the created project.
2Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.
3Because you are using Java-based annotations, so you also need to add CGLIB.jar from your Java installation directory and ASM.jar library which can be downloaded from asm.ow2.org.
4Create Java classes TextEditorConfigTextEditorSpellChecker and MainApp under thecom.yiibai package.
5The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

这里是TextEditorConfig.java文件的内容:

package com.yiibai;import org.springframework.context.annotation.*;@ConfigurationpublicclassTextEditorConfig{@BeanpublicTextEditor textEditor(){returnnewTextEditor( spellChecker());}@BeanpublicSpellChecker spellChecker(){returnnewSpellChecker();}}

这里是TextEditor.java文件的内容:

package com.yiibai;publicclassTextEditor{privateSpellChecker spellChecker;publicTextEditor(SpellChecker spellChecker){System.out.println("Inside TextEditor constructor.");this.spellChecker = spellChecker;}publicvoid spellCheck(){
      spellChecker.checkSpelling();}}

下面是另外一个相关的类文件SpellChecker.java内容:

package com.yiibai;publicclassSpellChecker{publicSpellChecker(){System.out.println("Inside SpellChecker constructor.");}publicvoid checkSpelling(){System.out.println("Inside checkSpelling.");}}

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

package com.yiibai;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.*;publicclassMainApp{publicstaticvoid main(String[] args){ApplicationContext ctx =newAnnotationConfigApplicationContext(TextEditorConfig.class);TextEditor te = ctx.getBean(TextEditor.class);

      te.spellCheck();}}

创建所有的源文件并添加所需的额外的库完成,让我们运行应用程序。应该注意,不需要配置文件。如果一切顺利,这将打印以下信息:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.
@Import 注解:

@ import的注解允许加载@Bean从另一个配置类定义。考虑一个配置类,如下所示: 

@ConfigurationpublicclassConfigA{@Beanpublic A a(){returnnew A();}}

您可以在另一个bean声明导入上述bean声明如下:

@Configuration@Import(ConfigA.class)publicclassConfigB{@Beanpublic B a(){returnnew A();}}

现在,不需要实例化的前提下,当同时指定配置A.class和配置B.class,只有Config B类需要如下提供:

publicstaticvoid main(String[] args){ApplicationContext ctx =newAnnotationConfigApplicationContext(ConfigB.class);// now both beans A and B will be available...
   A a = ctx.getBean(A.class);
   B b = ctx.getBean(B.class);}
生命周期回调:

@Bean注解支持指定任意的初始化和销毁​​回调方法,就像Spring的XML的初始化方法和bean元素销毁方法的属性:

publicclassFoo{publicvoid init(){// initialization logic}publicvoid cleanup(){// destruction logic}}@ConfigurationpublicclassAppConfig{@Bean(initMethod ="init", destroyMethod ="cleanup")publicFoo foo(){returnnewFoo();}}
指定Bean的适用范围:

默认范围是单例,但可以使用@Scope注解来覆盖此如下:

@ConfigurationpublicclassAppConfig{@Bean@Scope("prototype")publicFoo foo(){returnnewFoo();}}

  • 发表于 2017-11-24 21:20
  • 阅读 ( 1808 )
  • 分类:Java

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
不写代码的码农
江南烟雨

可以跨境界的java开发攻城狮

36 篇文章

作家榜 »

  1. 威猛的小站长 124 文章
  2. Jonny 65 文章
  3. 江南烟雨 36 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 22 文章
  8. Alan 14 文章