首页 > 学院 > 开发设计 > 正文

spring学习

2019-11-14 15:19:35
字体:
来源:转载
供稿:网友
<!--使用外部属性文件链接数据库--!>
<
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=rootpassword=123456driverclass=com.MySQL.jdbc.Driverjdbcurl=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           //这就是整个生命周期的流程


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表