配置bean之你使用外部属性

来源:互联网 发布:linux常用命令kill 编辑:程序博客网 时间:2024/05/20 20:01

beans-properties.xml:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns: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.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 导入属性文件 --><context:property-placeholder location="classpath:db.properties"/>    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">    <!-- 使用外部化文件的属性 有点像el表达式-->        <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></beans>

在上面代码中,属性的赋值用到了.properties文件中的内容。
db.properties:

user=rootpassword=1230driverclass=com.mysql.jdbc.Driverjdbcurl=jdbc:mysql///test

.properties文件都是以键值对的形式存在。
main.java:

package com.atguigu.spring.beans.properties;import java.sql.SQLException;import javax.sql.DataSource;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {    public static void main(String[] args) throws SQLException {        ApplicationContext c=new ClassPathXmlApplicationContext("beans-properties.xml");        DataSource dataSource=(DataSource)c.getBean("dataSource");        System.out.println(dataSource.getConnection());    }}
0 0
原创粉丝点击