spring学习

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

<!--使用外部属性文件链接数据库--!>

<context:PRoperty-placeholderlocation="db.properties"/>

<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"><!--使用外部属性文件--><propertyname="user"value="${user}"></property><propertyname="passWord"value="${password}"></property><propertyname="driverClass"value="${driverclass}"></property><propertyname="jdbcUrl"value="${jdbcurl}"></property></bean>

在部署系统时需要一些细节信息,这些信息放在spring中后期不方便,需要外部属性文件,spring提供了一个PropertyPlaceholderConfigurer的后置处理器,它允许用户将bean配置的内容外移到属性文件中,写好配置文件后,在访问属性时用"${var}"访问(注意要先导入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=root

password=123456

driverclass=com.MySQL.jdbc.Driver

jdbcurl=jdbc:mysql:///hibernate

SpEL(Spring表达式语言)

#{}为bean属性的动态赋值提供了便利,用SpEL你当然可以引用字面量,但这没什么卵用,也可以引用对象,其他对象的属性,类的静态变量等等

<beanid="car"class="com.autowire.Car"scope="prototype"><propertyname="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>

<!--甚至于可以动态赋值--!>

</bean>

IOC中Bean的生命周期:

容器可以管理对象的生命周期,下面这个例子可以看出IOC管理对象的过程:

publicclassCar{2publicCar(){3 System.out.println("car's constructor");4}5publicvoidsetBrand(String brand){6 System.out.println("setBrand")7}8publicvoidinit(){9 System.out.println("car's init");10}11publicvoiddestory(){12 System.out.println("car's destory");13 }

<!--创建对象以测试--!>

<beanid="car"class="com.process.Car"init-method="init"destroy-method="destory"><propertyname="brand"value="Audi"></property></bean>

publicstaticvoidmain(String[] args) {//TODO Auto-generated method stubClassPathXmlApplicationContext ctx =newClassPathXmlApplicationContext("bean-process.xml");

Car car= (Car) ctx.getBean("car");

System.out.println(car);

ctx.close(); //测试方法

结果:

car's constructor

setBrand

car's init

com.process.Car@3a8624

car's destory //这就是整个生命周期的流程

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航