<!--使用外部屬性文件鏈接數(shù)據(jù)庫--!>
<context:PRoperty-placeholder location="db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <!-- 使用外部屬性文件 --> <property name="user" value="${user}"></property> <property name="passWord" value="${password}"></property> <property name="driverClass" value="${driverclass}"></property> <property name="jdbcUrl" value="${jdbcurl}"></property></bean>
在部署系統(tǒng)時(shí)需要一些細(xì)節(jié)信息,這些信息放在spring中后期不方便,需要外部屬性文件,spring提供了一個(gè)PropertyPlaceholderConfigurer的后置處理器,它允許用戶將bean配置的內(nèi)容外移到屬性文件中,寫好配置文件后,在訪問屬性時(shí)用"${var}"訪問(注意要先導(dǎo)入context命名空間)
public static void main(String[] args) throws SQLException { applicationContext ctx = new ClassPathxmlApplicationContext("beans-properties.xml"); DataSource dataSource = (DataSource) ctx.getBean("dataSource"); System.out.println(dataSource.getConnection()); }
user=rootpassword=123456driverclass=com.MySQL.jdbc.Driverjdbcurl=jdbc:mysql:///hibernate
SpEL(Spring表達(dá)式語言)
#{}為bean屬性的動態(tài)賦值提供了便利,用SpEL你當(dāng)然可以引用字面量,但這沒什么卵用,也可以引用對象,其他對象的屬性,類的靜態(tài)變量等等
<bean id="car" class="com.autowire.Car" scope="prototype"> <property name="car" value=#{audi}></property> <property name="tyrePremeter" value="#{T(java.lang.Math).PI*80}"></property>
<property name="brand" value=#{brand.name}</property>
<property name="price" value=#{300000}></property>
<property name="info" value="#{price>400000?'高富帥':'屌絲'}"></property>
<!--甚至于可以動態(tài)賦值--!>
</bean>
IOC中Bean的生命周期:
容器可以管理對象的生命周期,下面這個(gè)例子可以看出IOC管理對象的過程:
public class Car{ 2 public Car(){ 3 System.out.println("car's constructor"); 4 } 5 public void setBrand(String brand){ 6 System.out.println("setBrand") 7 } 8 public void init(){ 9 System.out.println("car's init");10 } 11 public void destory(){12 System.out.println("car's destory");13 }
<!--創(chuàng)建對象以測試--!>
<bean id="car" class="com.process.Car" init-method="init" destroy-method="destory"> <property name="brand" value="Audi"></property></bean>
public static void main(String[] args) { // TODO Auto-generated method stub ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bean-process.xml"); Car car = (Car) ctx.getBean("car"); System.out.println(car); ctx.close(); //測試方法
結(jié)果:
car's constructor
setBrand
car's init
com.process.Car@3a8624
car's destory //這就是整個(gè)生命周期的流程
新聞熱點(diǎn)
疑難解答
圖片精選