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

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


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

步驟 描述
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文件的內容:


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

這裏是HelloWorld.java的文件的內容:


package com.yiibai;
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.yiibai;
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的依賴關係:

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


package com.yiibai;
import org.springframework.context.annotation.*;
@Configuration
public class AppConfig {
@Bean
public Foo foo() {
return new Foo(bar());
}
@Bean
public Bar bar() {
return new Bar();
}
}

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

例子:

讓我們使用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 TextEditorConfig, TextEditor, SpellChecker and MainApp under thecom.yiibai 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.yiibai;
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.yiibai;
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.yiibai;
public class SpellChecker {
public SpellChecker(){
System.out.println("Inside SpellChecker constructor." );
}
public void checkSpelling(){
System.out.println("Inside checkSpelling." );
}
}

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


package com.yiibai;
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 註解:

@ import的註解允許加載@Bean從另一個配置類定義。考慮一個配置類,如下所示:


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

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


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

現在,不需要實例化的前提下,當同時指定配置A.class和配置B.class,只有Config B類需要如下提供:


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


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

原文發佈時間爲:2018-10-25
本文來自雲棲社區合作伙伴“Java雜記”,瞭解相關信息可以關注“Java雜記”。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章