天天看點

Spring 基于Java配置

到目前為止,您已經了解了如何配置使用XML配置檔案的Spring bean。如果習慣使用XML配置,那麼會說,這不是真的需要學習如何進行基于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.*;

@Configuration

public class HelloWorldConfig {

@Bean

public HelloWorld helloWorld(){

return new HelloWorld();

}

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

<beans>

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

</beans>

下面注解為@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();

可以加載各種配置類别如下:

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應用程式:

步驟 描述
1 Create a project with a name SpringExample and create a package com.yiibai 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.yiibaipackage.
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檔案的内容:

}

}

這裡是HelloWorld.java的檔案的内容:

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檔案的内容:

import org.springframework.context.ApplicationContext;

public class MainApp {

public static void main(String[] args) {

建立所有的源檔案并添加所需的額外(外部)的庫,讓我們運作應用程式。應該注意,不需要配置檔案。如果一切順利,這将列印以下資訊:

Your Message : Hello World!       

注入Bean的依賴關系:

當@Bean對彼此的依賴,表達這種依賴很簡單,隻要有一個Bean的方法調用另一個如下:

@Configuration

public class AppConfig {

public Foo foo() {

return new Foo(bar());

public Bar bar() {

return new Bar();

在這裡,Bean接收基準通過構造函數注入。現在,讓我們看到一個正常工作的例子:

Create Java classes TextEditorConfig, TextEditor, SpellChecker and MainApp under thecom.yiibai package.

這裡是TextEditorConfig.java檔案的内容:

public class TextEditorConfig {

public TextEditor textEditor(){

return new TextEditor( spellChecker() );

public SpellChecker spellChecker(){

return new SpellChecker( );

這裡是TextEditor.java檔案的内容:

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内容:

public class SpellChecker {

public SpellChecker(){

System.out.println("Inside SpellChecker constructor." );

public void checkSpelling(){

System.out.println("Inside checkSpelling." );

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從另一個配置類定義。考慮一個配置類,如下所示:

@Configuration

public class ConfigA {

public A a() {

return new A();

您可以在另一個bean聲明導入上述bean聲明如下:

@Import(ConfigA.class)

public class ConfigB {

public B a() {

現在,不需要執行個體化的前提下,當同時指定配置A.class和配置B.class,隻有Config B類需要如下提供:

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元素銷毀方法的屬性:

public class Foo {

public void init() {

// initialization logic

public void cleanup() {

// destruction logic

@Configuration

public class AppConfig {

@Bean(initMethod = "init", destroyMethod = "cleanup" )

return new Foo();

指定Bean的适用範圍:

預設範圍是單例,但可以使用@Scope注解來覆寫此如下:

@Scope("prototype")

原文釋出時間為:2018-10-25

本文來自雲栖社群合作夥伴“

Java雜記

”,了解相關資訊可以關注“

”。

繼續閱讀