Spring
1. 三種實例化bean的方法
1) 第一種是使用類構造器實例化;
[html]
<bean id="personService"class="com.lcq.service.impl.PersonServiceBean"></bean>
2) 第二種是使用靜態工廠方法實例化;
[html]
<beanidbeanid="personService1"class="com.lcq.service.impl.PersonServiceBeanFactory"
y-method="createPersonServiceBean"></bean>
3) 第三種是使用實例工廠方法實例化;
[html]
<bean id="PersonServiceBeanFactory"class="com.lcq.service.impl.PersonServiceBeanFactory"></bean>
<bean id="personService2" factoryfactory-bean="PersonServiceBeanFactory"factory-method="createPersonServiceBean2"></bean>
2. bean的作用域,默認的情況之下,spring容器的bean的作用域是單實例的,也就是說當我們從容器中得到的bean實例是同一個。可以使用scope標簽設置bean的作用域為原型,也就是說每次得到的bean是不同的對象實例。scope="prototype"。註意默認情況下的bean是在spring容器實例化的時候就進行實例化的;當是原型時bean的實例化是在getbean的時候進行實例化的。也可以在xml中配置bean的加載時機為延遲。
3. spring的依賴註入之使用屬性setter方法實現註入:ref標簽或者使用內部bean
1)
[html]
<bean id="personDao" class="com.lcq.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="com.lcq.service.impl.PersonServiceBean"
init-method="init"destroy-method="destory">
<property name="personDao" ref="personDao"></property>
</bean>
2)
[html]
<bean id="personService"class="com.lcq.service.impl.PersonServiceBean"
init-method="init"destroy-method="destory">
<property name="personDao" >
<bean class="com.lcq.dao.impl.PersonDaoBean"/>
</ property>
</bean>
配置xml實現spring註入Set和Map等集合類型。
[html]
<property name="sets">
<set>
<value>第一個</value>
<value>第二個</value>
<value>第三個</value>
</set>
</property>
<property name="maps">
<map>
<entry key="key1" value="value1"/>
<entry key="key2" value="value2"/>
<entry key="key3" value="value3"/>
</map>
</property>
4. 使用構造器實現註入
5. 使用註解進行註入
6. 使用註解將bean添加到spring的管理中。
在xml中配置:
[html]
<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlnsxmlns: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-2.5.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.lcq"/>
</beans>
這樣spring容器會在啟動時將在指定的包的目錄下進行查詢查到所有相關的bean對其進行加載和註入。
在相應的需要加載的bean定義的前面添加註解進行標識。
[java]
//使用註解將bean添加到spring容器的管理中
@Service @Scope("prototype")
public class PersonDaoBean implements PersonDao {
//利用註解實現對象初始化操作
@PostConstruct
public void init(){
System.out.println("initinvoked");
}
public void add(){
System.out.println("add methodis invoked!");
}
}
摘自 liuchangqing123