Spring 基于 Java 的配置

2022-05-16 15:28 更新

基于 Java 的配置

到目前為止,你已經(jīng)看到如何使用 XML 配置文件來(lái)配置 Spring bean。如果你熟悉使用 XML 配置,那么我會(huì)說(shuō),不需要再學(xué)習(xí)如何進(jìn)行基于 Java 的配置是,因?yàn)槟阋_(dá)到相同的結(jié)果,可以使用其他可用的配置。

基于 Java 的配置選項(xiàng),可以使你在不用配置 XML 的情況下編寫大多數(shù)的 Spring,但是一些有幫助的基于 Java 的注解,解釋如下:

@Configuration 和 @Bean 注解

帶有 @Configuration 的注解類表示這個(gè)類可以使用 Spring IoC 容器作為 bean 定義的來(lái)源。@Bean 注解告訴 Spring,一個(gè)帶有 @Bean 的注解方法將返回一個(gè)對(duì)象,該對(duì)象應(yīng)該被注冊(cè)為在 Spring 應(yīng)用程序上下文中的 bean。最簡(jiǎn)單可行的 @Configuration 類如下所示:

package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

上面的代碼將等同于下面的 XML 配置:

<beans>
   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld" />
</beans>

在這里,帶有 @Bean 注解的方法名稱作為 bean 的 ID,它創(chuàng)建并返回實(shí)際的 bean。你的配置類可以聲明多個(gè) @Bean。一旦定義了配置類,你就可以使用 AnnotationConfigApplicationContext 來(lái)加載并把他們提供給 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();
}

例子

讓我們?cè)谇‘?dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟來(lái)創(chuàng)建一個(gè) Spring 應(yīng)用程序:

步驟描述
1創(chuàng)建一個(gè)名稱為 SpringExample 的項(xiàng)目,并且在創(chuàng)建項(xiàng)目的 src 文件夾中創(chuàng)建一個(gè)包 com.tutorialspoint。
2使用 Add External JARs 選項(xiàng),添加所需的 Spring 庫(kù),解釋見(jiàn) Spring Hello World Example 章節(jié)。
3因?yàn)槟闶鞘褂没?java 的注解,所以你還需要添加來(lái)自 Java 安裝目錄的 CGLIB.jar 和可以從 asm.ow2.org 中下載的 ASM.jar 庫(kù)。
4com.tutorialspoint 包中創(chuàng)建 Java 類 HelloWorldConfig、HelloWorldMainApp
5最后一步是創(chuàng)建的所有 Java 文件和 Bean 配置文件的內(nèi)容,并運(yùn)行應(yīng)用程序,解釋如下所示。

這里是 HelloWorldConfig.java 文件的內(nèi)容:

package com.tutorialspoint;
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
   @Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }
}

這里是 HelloWorld.java 文件的內(nèi)容:

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 文件的內(nèi)容:

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();
   }
}

一旦你完成了創(chuàng)建所有的源文件并添加所需的額外的庫(kù)后,我們就可以運(yùn)行該應(yīng)用程序。你應(yīng)該注意這里不需要配置文件。如果你的應(yīng)用程序一切都正常,將輸出以下信息:

Your Message : Hello World!

注入 Bean 的依賴性

當(dāng) @Beans 依賴對(duì)方時(shí),表達(dá)這種依賴性非常簡(jiǎn)單,只要有一個(gè) bean 方法調(diào)用另一個(gè),如下所示:

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 通過(guò)構(gòu)造函數(shù)注入來(lái)接收參考基準(zhǔn)?,F(xiàn)在,讓我們看到一個(gè)正在執(zhí)行的例子:

例子:

讓我們?cè)谇‘?dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟來(lái)創(chuàng)建一個(gè) Spring 應(yīng)用程序:

步驟描述
1創(chuàng)建一個(gè)名稱為 SpringExample 的項(xiàng)目,并且在創(chuàng)建項(xiàng)目的 src 文件夾中創(chuàng)建一個(gè)包 com.tutorialspoint。
2使用 Add External JARs 選項(xiàng),添加所需的 Spring 庫(kù),解釋見(jiàn) Spring Hello World Example 章節(jié)。
3因?yàn)槟闶鞘褂没?java 的注解,所以你還需要添加來(lái)自 Java 安裝目錄的 CGLIB.jar 和可以從 asm.ow2.org 中下載的 ASM.jar 庫(kù)。
4com.tutorialspoint 包中創(chuàng)建 Java 類 TextEditorConfig、TextEditorSpellCheckerMainApp。
5最后一步是創(chuàng)建的所有 Java 文件和 Bean 配置文件的內(nèi)容,并運(yùn)行應(yīng)用程序,解釋如下所示。

這里是 TextEditorConfig.java 文件的內(nèi)容:

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 文件的內(nèi)容:

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();
   }
}

下面是另一個(gè)依賴的類文件 SpellChecker.java 的內(nèi)容:

package com.tutorialspoint;
public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }
   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }

}

下面是 MainApp.java 文件的內(nèi)容:

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();
   }
}

一旦你完成了創(chuàng)建所有的源文件并添加所需的額外的庫(kù)后,我們就可以運(yùn)行該應(yīng)用程序。你應(yīng)該注意這里不需要配置文件。如果你的應(yīng)用程序一切都正常,將輸出以下信息:

Inside SpellChecker constructor.
Inside TextEditor constructor.
Inside checkSpelling.

@Import 注解:

@import 注解允許從另一個(gè)配置類中加載 @Bean 定義??紤] ConfigA 類,如下所示:

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

你可以在另一個(gè) Bean 聲明中導(dǎo)入上述 Bean 聲明,如下所示:

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

現(xiàn)在,當(dāng)實(shí)例化上下文時(shí),不需要同時(shí)指定 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);
}

生命周期回調(diào)

@Bean 注解支持指定任意的初始化和銷毀的回調(diào)方法,就像在 bean 元素中 Spring 的 XML 的初始化方法和銷毀方法的屬性:

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 的范圍:

默認(rèn)范圍是單實(shí)例,但是你可以重寫帶有 @Scope 注解的該方法,如下所示:

@Configuration
public class AppConfig {
   @Bean
   @Scope("prototype")
   public Foo foo() {
      return new Foo();
   }
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)