spring-8- 第三方资源配置管理案例

管理第三方资源配置

配置pom.xml

<!--1、导入Druid !-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.16</version>
        </dependency>
        <!--导入c3p0-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

配置applicationContext文件

<!--    3、管理DruidDataSource对象-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/a"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!-- 4、 管理C3p0!-->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/a"/>
        <property name="user" value="root"/>
        <property name="password" value="123456"/>
    </bean>

app文件

DataSource dataSource = (DataSource) ctx.getBean("dataSource");
 System.out.println(dataSource);

我们不会把jdbc的URL等写在pom.xml中,一般都写在jdbc.properties中,那我们要怎么在applicationContext2中获取到properties中的内容呢。

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/a
jdbc.username=root
jdbc.password=123456

1、开启context命名空间

<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.xsd">

2、使用context命名空间,加载指定的properties文件

<!--    开启context命名空间-->
<!--    使用context空间加载properties文件-->
<context:property-placeholder location="jdbc.properties"/>

3、用${}读值

<bean id="BookDao" class="com.itheima.dao.impl.BookDaoImpl">
        <property name="name" value="${jdbc.url}"/>
    </bean>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容