1. 程式人生 > >基於java的Spring容器配置(二)(@Configuration,@Bean,@Import,@ImportSource)

基於java的Spring容器配置(二)(@Configuration,@Bean,@Import,@ImportSource)

@Bean的使用

 @Bean是一個方法級別的註解類似於XML的元素,這個註解提供了一些的屬性例如 init-method, destroy-method, autowiring 和name
 應用場合:@Configuration註解或者@Component註解的類

宣告一個Bean

為了宣告一個Bean簡單的在方法上註冊一個@Bean註解,用這種方式在ApplicationContext介面下注冊一個具體型別的Bean

@Component//@Configuration
public class BasedJava {
@Bean
public Hello hello(){
    return new Hello();
}
}

等同於:

<beans>
 <bean id="hello" class="com.hello"/>
</beans>

實現生命週期中的回撥函式

 所有用@Bean註解的類均支援常規的生命週期回撥函式並且可以使用JSR-250標準中的註解,如果一個Bean實現了 InitializingBean DisposableBean,他們相應的方法也會被容器呼叫
 @Bean支援具體的任意的初始化和銷燬的回撥函式類似於Spring XML中Bean元素上面的init-method和destory-method屬性

@Component
public class BasedJava {
@Bean(initMethod = "init",destroyMethod = "destoryBean")
public Hello hello(){
    return new Hello();
}
}

使用@Scope指定Bean的作用域

@scope預設為singleton即單例模式,當然也可以更改其值為**多例模式**prototype,在Spring 2.0之後,為支援web應用的ApplicationContext,增強另外三種:request,session和global session型別,它們只實用於web程式,通常是和XmlWebApplicationContext共同使用。後續在Spring MVC的學習中將會再詳細介紹。

自定義Bean的名字

@Component
public class BasedJava {
@Bean(initMethod = "init",destroyMethod = "destoryBean",name = "hello")
public Hello hello(){
    return new Hello();
}
}

為Bean定義別名(將一個字串陣列賦值給name屬性)

@Component
public class BasedJava {
@Bean(initMethod = "init",destroyMethod = "destoryBean",name = {"hello1","hello2","hello3"})
public Hello hello(){
    return new Hello();
}
}

為Bean定義新增描述

為Bean新增文字描述可以方便在Bean的管理

@Component
public class BasedJava {
@Bean(initMethod = "init",destroyMethod = "destoryBean",name = {"hello1","hello2","hello3"})
@Description("spring bean ")
public Hello hello(){
    return new Hello();
}
}

使用@Configuration註解

@Configuration是一個類級別的註解它用來指示一個物件是Bean定義的來源,@Configuration通過@Bean註釋的方法宣告Bean,在配置類裡面的@Bean註釋的方法也可以用來宣告內部的Bean依賴,但不可以在@Component註解的類裡面使用@Bean宣告內部的Bean依賴。(在上篇博文有更加詳細的介紹)

附加的Java基礎的配置

使用@import註解

正如元素是在Spring XML檔案中幫助模組化配置,@Import註解允許從其他的裝載類中載入@Bean定義的類

@Component
@Import( BasedJava2.class)
public class BasedJava {
@Bean(initMethod = "init",destroyMethod = "destoryBean",name = {"hello1","hello2","hello3"})
@Description("spring bean ")
public Hello hello(){
    return new Hello();
}
}

@Component
public class BasedJava2 {
@Bean
@Description("spring bean ")
public ComponentTest componentTest(){
    return new  ComponentTest();
}
}



    AnnotationConfigApplicationContext appl=new AnnotationConfigApplicationContext(BasedJava.class);

//ComponentTest類的測試
ComponentTest com= appl.getBean(ComponentTest.class);
com.setName("@component");
com.setId(88);
System.out.println(com.toString());

//Hello類的測試
Hello hello= appl.getBean(Hello.class);
hello.setMessage("hello class 測試");
System.out.println(hello.getMessage());

由此看出只要指定明確的了BaseJava類進行處理就可以呼叫BaseJava2中的bean,而不需要指定BaseJava BaseJava2兩個類

@Configuration 下用@ImportResource匯入XML資訊

 在應用中@Configuration 註解類是容器基本的機制,仍然很有必要的去利用一些XML檔案,在這些情節中,簡單的使用@ImportResource並且定義一些XML檔案是需要的。按照這種方式實現以java為中心的配置容器的方法,並且使XML最少

ImportSourceDemo.java

package com.demo.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

/**
 * Created by ruanjianlin on 2017/10/10.
 */
    @Configuration
@ImportResource("classpath*:importSource.xml")
public class ImportSourceDemo {
@Value("${JDBC.URL}")
private String url;

@Value("${JDBC.PASSWORD}")
private String password;

@Value("${JDBC.USER}")
private String user;

@Bean
public JdbcConnect jdbcConnect(){
    return new JdbcConnect(url,password,user);

}
}


JdbcConnect.java
package com.demo.configuration;

/**
 * Created by ruanjianlin on 2017/10/10.
 */
public class JdbcConnect {
private String url;
private String password;
private String user;

public JdbcConnect(String url, String password, String user) {
    this.url = url;
    this.password = password;
    this.user = user;
}

@Override
public String toString() {
    return "JdbcConnect{" + "url='" + url + '\'' + ", password='" + password + '\'' + ", user='" + user + '\'' + '}';
}
}

xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"/>
</beans>

Jdbc.properties
jdbc.url=jdbc:mysql:mysql://localhost/spring
jdbc.username=test
jdbc.password=test

注:“classpath”: 用於載入類路徑(包括jar包)中的一個且僅一個資源;對於多個匹配的也只返回一個,所以如果需要多個匹配的請考慮“classpath*:”字首;