📜  春季-基于Java的配置

📅  最后修改于: 2020-11-11 07:04:43             🧑  作者: Mango


到目前为止,您已经了解了我们如何使用XML配置文件配置Spring bean。如果您对XML配置感到满意,那么实际上不需要学习如何进行基于Java的配置,因为您将使用两种可用的配置来达到相同的结果。

基于Java的配置选项使您无需XML即可编写大部分Spring配置,而借助本章中介绍的基于Java的注释很少。

@Configuration和@Bean批注

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

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

上面的代码将等效于以下XML配置-


   

在这里,方法名称用@Bean标注为bean ID,它创建并返回实际的bean。您的配置类可以具有多个@Bean的声明。一旦定义了配置类,就可以使用AnnotationConfigApplicationContext将它们加载并提供给Spring容器,如下所示-

public static void main(String[] args) {
   ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConfig.class);
   
   HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
   helloWorld.setMessage("Hello World!");
   helloWorld.getMessage();
}

您可以按如下方式加载各种配置类:

public static void main(String[] args) {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

   ctx.register(AppConfig.class, OtherConfig.class);
   ctx.register(AdditionalConfig.class);
   ctx.refresh();

   MyService myService = ctx.getBean(MyService.class);
   myService.doStuff();
}

让我们拥有一个运行良好的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 Because 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.
4 Create Java classes HelloWorldConfig, HelloWorld and MainApp under the com.tutorialspoint package.
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.

这是HelloWorldConfig.java文件的内容

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

这是HelloWorld.java文件的内容

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}

以下是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(HelloWorldConfig.class);
   
      HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
      helloWorld.setMessage("Hello World!");
      helloWorld.getMessage();
   }
}

创建完所有源文件并添加所需的其他库后,让我们运行该应用程序。您应该注意,不需要配置文件。如果您的应用程序一切正常,它将打印以下消息:

Your Message : Hello World!

注入Bean依赖关系

当@Beans具有彼此依赖关系时,表示依赖关系就像让一个bean方法调用另一个一样简单,如下所示:

package com.tutorialspoint;
import org.springframework.context.annotation.*;

@Configuration
public class AppConfig {
   @Bean
   public Foo foo() {
      return new Foo(bar());
   }
   @Bean
   public Bar bar() {
      return new Bar();
   }
}

在这里,foo bean通过构造函数注入接收对bar的引用。现在让我们看另一个工作示例。

让我们拥有一个运行良好的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 Because 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.
4 Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under the com.tutorialspoint package.
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.

这是TextEditorConfig.java文件的内容

package com.tutorialspoint;
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.java文件的内容

package com.tutorialspoint;

public class TextEditor {
   private SpellChecker spellChecker;

   public TextEditor(SpellChecker spellChecker){
      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注释允许从另一个配置类加载@Bean定义。考虑如下的ConfigA类-

@Configuration
public class ConfigA {
   @Bean
   public A a() {
      return new A(); 
   }
}

您可以在另一个Bean声明中的Bean声明上方导入,如下所示-

@Configuration
@Import(ConfigA.class)
public class ConfigB {
   @Bean
   public B b() {
      return new B(); 
   }
}

现在,无需在实例化上下文时同时指定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注释支持指定任意的初始化和销毁回调方法,就像Spring XML在bean元素上的init-method和destroy-method属性一样-

public class Foo {
   public void init() {
      // initialization logic
   }
   public void cleanup() {
      // destruction logic
   }
}
@Configuration
public class AppConfig {
   @Bean(initMethod = "init", destroyMethod = "cleanup" )
   public Foo foo() {
      return new Foo();
   }
}

指定Bean范围

默认范围是单例,但是您可以使用@Scope注释覆盖此范围,如下所示:

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}