Spring中Bean的基本用法__spring

來源:互聯網
上載者:User

1.引用Bean

<ref bean="someBean"/>

如:

<bean id="A" class="com.B"><property name="C" ><ref bean="C1"/></property></bean>


2.需指定必定是同個XML下的Bean時,用

<ref local="someBean"/>

3.屬性值的注入

<bean id="AAA" class="com.BB"><property name="name"><value>XXX</value></property><property name="type"><value>txt</value></property></bean>//或者<bean id="AAA" class="com.BB"><property name="name" value="XXX" /><property name="type" value="txt" /></bean>


使用P模型

xmlns:p="http://www.springframework.org/schema/p"
<bean id="AAA" class="com.BB" p:name="XXX" p:type="txt" />

這樣更加簡便

4.引入多個XML檔案

通過內含項目關聯性

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><import resource="common/Spring-Common.xml"/>        <import resource="connection/Spring-Connection.xml"/>        <import resource="moduleA/Spring-ModuleA.xml"/></beans>

指定目錄,參考是class根目錄

ApplicationContext context =     new ClassPathXmlApplicationContext(new String[] {"Spring-Common.xml",              "Spring-Connection.xml","Spring-ModuleA.xml"});

5.內嵌Bean時

<bean id="XXX" class="com.AAA"><property name="person"><bean class="com.BB"><property name="name" value="YY" /><property name="age" value="22" /></bean></property></bean>

指的是在AAA類中,有個person屬性的Persion類,我們使用set的方式注入一個建立的Persion的Bean對象,我們也可以用構造器的方式注入

<bean id="XXX" class="com.AAA"><constructor-arg><bean class="com.Person"><property name="name" value="mkyong" /><property name="age" value="28" /></bean></constructor-arg></bean>

注意的是不要在Person的單獨bean對象中注入persion的屬性,而是通過上面的方式建立一個臨時bean注入XXXbean中

6.bean的scope設定
5種配置

singleton 始終返回一個單一的Bean對象prototype 每次都返回一個新的bean對象request          通過HTTP request.請求返回單一的beansession          通過HTTP session.請求返回單一的beanglobalSession     通過全域HTTP session.請求返回單一的bean

3.0時預設配置是singleton
設定時只要在bean的屬性裡設定,例如設定prototype

scope="prototype"

或者通過Anno註解

@Scope("prototype")

7.集合

主要是這幾種,舉例

這裡是泛泰指定的時候,如List<Object> list屬性

List – <list/>Set – <set/>Map – <map/>Properties – <props/>
<property name="lists"><list><value>1</value><ref bean="PersonBean" /><bean class="com.Person"><property name="name" value="mkyongList" /><property name="age" value="33" /></bean></list></property>
<property name="sets"><set><value>1</value><ref bean="PersonBean" /><bean class="com.Person"><property name="name" value="mkyongSet" /><property name="age" value="28" /></bean></set></property>
<property name="maps"><map><entry key="Key 1" value="1" /><entry key="Key 2" value-ref="PersonBean" /><entry key="Key 3"><bean class="com.Person"><property name="name" value="mkyongMap" /><property name="age" value="28" /></bean></entry></map></property
<property name="pros"><props><prop key="admin">admin@nospam.com</prop><prop key="support">support@nospam.com</prop></props></property>>

8.集合(原廠模式)

上面我們是指定List等的類型類的類型,如果不制定的話,讓我們裝配一個全新的集合

private List lists;
<bean id="CustomerBean" class="com.Customer"><property name="lists"><bean class="org.springframework.beans.factory.config.ListFactoryBean"><property name="targetListClass"><value>java.util.ArrayList</value></property><property name="sourceList"><list><value>1</value><value>2</value><value>3</value></list></property></bean></property></bean>

我們通過
targetListClass指定list的類型類的類型

讓後開始填儲值

或者通過

xmlns:util=<a target=_blank href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a>

便簽

<bean id="CustomerBean" class="com.Customer"><property name="lists"><util:list list-class="java.util.ArrayList"><value>1</value><value>2</value><value>3</value></util:list></property></bean>


還有其他集合

Set

<bean id="CustomerBean" class="com.Customer"><property name="sets"><bean class="org.springframework.beans.factory.config.SetFactoryBean"><property name="targetSetClass"><value>java.util.HashSet</value></property><property name="sourceSet"><list><value>1</value><value>2</value><value>3</value></list></property></bean></property></bean>
<bean id="CustomerBean" class="com.mkyong.common.Customer"><property name="sets"><util:set set-class="java.util.HashSet"><value>1</value><value>2</value><value>3</value></util:set></property></bean>


Map

<bean id="CustomerBean" class="com.Customer"><property name="maps"><bean class="org.springframework.beans.factory.config.MapFactoryBean"><property name="targetMapClass"><value>java.util.HashMap</value></property><property name="sourceMap"><map><entry key="Key1" value="1" /><entry key="Key2" value="2" /><entry key="Key3" value="3" /></map></property></bean></property></bean>
<bean id="CustomerBean" class="com.Customer"><property name="maps"><util:map map-class="java.util.HashMap"><entry key="Key1" value="1" /><entry key="Key2" value="2" /><entry key="Key3" value="3" /></util:map></property></bean>


9.特殊的注入Data的bean

通過兩種方式

 

"原廠模式"

Date date;
<bean id="dateFormat" class="java.text.SimpleDateFormat"><constructor-arg value="yyyy-MM-dd" /></bean><bean id="customer" class="com.mkyong.common.Customer"><property name="date"><bean factory-bean="dateFormat" factory-method="parse"><constructor-arg value="2010-01-31" /></bean></property></bean>

通過

CustomDateEditor
<bean id="dateEditor"class="org.springframework.beans.propertyeditors.CustomDateEditor"><constructor-arg><bean class="java.text.SimpleDateFormat"><constructor-arg value="yyyy-MM-dd" /></bean></constructor-arg><constructor-arg value="true" /></bean><bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"><property name="customEditors"><map><entry key="java.util.Date"><ref local="dateEditor" /></entry></map></property></bean><bean id="customer" class="com.mkyong.common.Customer"><property name="date" value="2010-02-31" /></bean>


10.通過預留位置配置一些屬性

常用於資料庫等常修改屬性的Bean

建立properties檔案

如配置資料的屬性(都是放在class的根目錄裡的)

database.properties

jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mkyongjavajdbc.username=rootjdbc.password=password

引入

<bean  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location"><value>database.properties</value></property></bean>

使用

<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean>


11.繼承性,就是利用之前配置的Bean再進行配置

<bean id="BaseCustomerMalaysia" class="com.mkyong.common.Customer"><property name="country" value="Malaysia" /></bean><bean id="CustomerBean" parent="BaseCustomerMalaysia"><property name="action" value="buy" /><property name="type" value="1" /></bean>

如果禁止繼承,可以在bean進行限制abstract="true"

<bean id="BaseCustomerMalaysia" class="com.mkyong.common.Customer" abstract="true"><property name="country" value="Malaysia" /></bean>

12.注入的檢測

有時我們要讓一個bean的屬性全部被注入才可以使用,預設的情況下時none

有這些檢測規則

none           –  No dependency checking.
simple        –  If any properties of primitive type (int, long,double…) and collection types (map, list..) have not been set, UnsatisfiedDependencyException will be thrown.
objects       –  If any properties of object type have not been set, UnsatisfiedDependencyException will be thrown.
all                –  If any properties of any type have not been set, an UnsatisfiedDependencyException will be thrown.

public class Customer {private Person person;private int type;private String action;//getter and setter methods}
<bean id="CustomerBean" class="com.mkyong.common.Customer"          dependency-check="simple"><property name="person" ref="PersonBean" /><property name="action" value="buy" /></bean><bean id="PersonBean" class="com.mkyong.common.Person"><property name="name" value="mkyong" /><property name="address" value="address ABC" /><property name="age" value="29" /></bean>


由於Customer Bean的type屬性沒有裝配所以會失敗

而objects規則是檢驗Object(非簡單類型)對象是否被配置

<bean id="CustomerBean" class="com.mkyong.common.Customer"          dependency-check="objects"><property name="action" value="buy" /><property name="type" value="1" /></bean>


沒有裝配private Person person;同樣會出錯

為了簡便你也可以全域配置

舉例配置default-dependency-check="all"規則

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-dependency-check="all">

13.對於上面的檢測規則是應用與整個對象的,如果我們需要對某個屬性進行Check

@Requiredpublic void setPerson(Person person) {this.person = person;}

這需要註冊RequiredAnnotationBeanPostProcessor

這樣就餓可以

RequiredAnnotationBeanPostProcessor <beans ...xmlns:context="http://www.springframework.org/schema/context"...http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">...<context:annotation-config />...</beans>

14.設定bean的init-method and destroy-method回調

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="customerService" class="com.mkyong.customer.services.CustomerService" init-method="initIt" destroy-method="cleanUp">   <property name="message" value="i'm property message" /></bean></beans>
public class CustomerService{String message;public String getMessage() {  return message;}public void setMessage(String message) {  this.message = message;}public void initIt() throws Exception {  System.out.println("Init method after properties are set : " + message);}public void cleanUp() throws Exception {  System.out.println("Spring Container is destroy! Customer clean up");}}



或者註解的方式

@PostConstructpublic void initIt() throws Exception {  System.out.println("Init method after properties are set : " + message);}@PreDestroypublic void cleanUp() throws Exception {  System.out.println("Spring Container is destroy! Customer clean up");}


By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in bean configuration file

 

1. CommonAnnotationBeanPostProcessor

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /><bean id="customerService" class="com.mkyong.customer.services.CustomerService"><property name="message" value="i'm property message" /></bean></beans>


2. <context:annotation-config />

<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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd"><context:annotation-config /><bean id="customerService" class="com.mkyong.customer.services.CustomerService"><property name="message" value="i'm property message" /></bean></beans>


 










 









 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.