码迷,mamicode.com
首页 > 编程语言 > 详细

spring学习

时间:2015-10-24 22:00:35      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

<!--使用外部属性文件链接数据库--!>
<
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>

在部署系统时需要一些细节信息,这些信息放在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你当然可以引用字面量,但这没什么卵用,也可以引用对象,其他对象的属性,类的静态变量等等

<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>
<!--甚至于可以动态赋值--!>
</bean>

IOC中Bean的生命周期:

容器可以管理对象的生命周期,下面这个例子可以看出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   }

<!--创建对象以测试--!>
<
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();                             //测试方法

 

 

结果:

car‘s constructor
setBrand
car‘s init
com.process.Car@3a8624

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

spring学习

标签:

原文地址:http://www.cnblogs.com/showing/p/4907653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!