Spring_12_Spring基于java配置

Spring 基于java配置

到目前為止,你已經(jīng)看到如何使用XML配置文件類配置Spring bean. 如果你熟悉使用XML配置,那么我會,不需要再學(xué)習(xí)如何進行基于java的配置,也可以使用其他配置.

基于java的配置選擇,可以使你再不使用配置XML的情況下編寫大多數(shù)的Spring,但是一些有幫助的基于java的注解如下.

@Configuration 和@Bean 注解

帶有@Configuration的注解類表示這個類可以使用Spring IOC 容器作為bean定義的來源.@Bean 注解告訴Spring , 一個帶有@Bean 的注解方式將返回一個對象,該對象應(yīng)該被注冊為Spring 應(yīng)用程序上下文的bean.最簡單可行的@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)建并返回實際的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();
}

案例:

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

HelloWorldConfig.java

package com.tutorialspoint;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HelloWorldConfig {

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

    
}

HelloWorld.java

package com.tutorialspoint;

public class HelloWorld {
    private String message;

    public void getMessage() {
        System.out.println("message:"+message);
    }

    public void setMessage(String message) {
        this.message = message;
    }
    
}

MainApp.java

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(
                HelloWorldConfig.class);
        HelloWorld helloWorld = context.getBean(HelloWorld.class);
        helloWorld.setMessage("helloMessage");
        helloWorld.getMessage();
    }
}

輸出結(jié)果

message:helloMessage

注入Bean的依賴

當(dāng)@Bean 依賴對方時,表達這種依賴性非常簡單,只要有一個bean方法調(diào)用另一個,如下所示

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 通過構(gòu)造函數(shù)注入來接收參考基準(zhǔn).現(xiàn)在讓我們來看下一個例子.

例子:

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

TextEditorConfig.java

package com.tutorialspoint;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@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("TextEditor  類 的  構(gòu)造方法   ");
        this.spellChecker = spellChecker;
    }

    public void spellCheck() {
        spellChecker.checkSpelling();
    }

}

SpellChecker.java

package com.tutorialspoint;

public class SpellChecker {

    public SpellChecker() {
        System.out.println("SpellChecker  的  空參構(gòu)造方法");
    }

    public void checkSpelling() {
        System.out.println("  SpellChecker 類的   方法    checkSpelling()");
    }

}

MainApp.java

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(
                TextEditorConfig.class);
        TextEditor te = context.getBean(TextEditor.class);
        te.spellCheck();
    }
}

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

SpellChecker  的  空參構(gòu)造方法
TextEditor  類 的  構(gòu)造方法   
  SpellChecker 類的   方法    checkSpelling()

@Import 注解

@Import注解允許從另一個配置類中加載@Bean定義. 考慮ConfigA 類如下所示

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

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

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

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

默認范圍是單實例,但是你可以重寫帶有@Scope注解的該方法,如下所示

@Configuration
public class AppConfig {
    @Bean
    @Scope("prototype")
    public Foo foo() {
        return new Foo();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.1 Spring IoC容器和bean簡介 本章介紹了Spring Framework實現(xiàn)的控制反轉(zhuǎn)(IoC)...
    起名真是難閱讀 2,665評論 0 8
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 1.1 spring IoC容器和beans的簡介 Spring 框架的最核心基礎(chǔ)的功能是IoC(控制反轉(zhuǎn))容器,...
    simoscode閱讀 6,844評論 2 22
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,931評論 1 92
  • 今年2028年,今年也29歲了,而她的人生正如她的名字陸煙塵,如塵埃般渺小,黯淡無味,但又棄之可惜。 ...
    怡怡怡怡怡怡莎閱讀 316評論 0 0

友情鏈接更多精彩內(nèi)容