Loading

Spring 配置数据源-通过Bean配置 和Spring 加载配置文件

//"com.alibaba.druid.pool.DruidDataSource"为数据源的对象应用目录
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/music"></property>
                <property name="username" value="root"></property>
                <property name="password" value="123"></property>
        </bean>

使用

       ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource dataSource =(DataSource) app.getBean("dataSource");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

Spring 加载配置文件

首先,需要引入context命名空间和约束路径:

命名空间:xmlns:context="http://www.springframework.org/schema/context"
约束路径:http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd

然后加载配置文件,通过spel表达式 写入属性

         <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
       <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
        </bean>
posted @ 2022-03-14 20:34  冰莫莫  阅读(244)  评论(0编辑  收藏  举报