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>
本文来自博客园,作者:冰莫莫,转载请注明原文链接:https://www.cnblogs.com/icemomo/p/16005863.html

浙公网安备 33010602011771号