品牌化战略的重要性,关键词优化公司兴田德润优惠吗,浙江网站建站,丹东做网站的在这里使用alibaba的druid来连接数据库#xff0c;然后再Spring Config下配置数据库 目录 第一步#xff1a;在pom.xml中导入坐标第二步#xff1a;在bean中配置连接注 第一步#xff1a;在pom.xml中导入坐标
在dependencies下写#xff1a; dependencygrou…在这里使用alibaba的druid来连接数据库然后再Spring Config下配置数据库 目录 第一步在pom.xml中导入坐标第二步在bean中配置连接注 第一步在pom.xml中导入坐标
在dependencies下写 dependencygroupIdcom.alibaba/groupIdartifactIddruid/artifactIdversion1.1.21/version/dependency重新导入一下就可以看到已经把这个包加载进来了
第二步在bean中配置连接
之前说过要完成注入可以使用setter注入以及构造注入。 点进这个包里面看一下它的构造方法能否允许我们使用构造注入
并没有合适的地方让我们输入一些连接相关的信息所以只能选择setter注入 在文件里面搜索一下set方法 发现可以通过set设置driverClassName、url、username、password 于是我们就使用setter注入的方式配置配置文件
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdbean iddataSource classcom.alibaba.druid.pool.DruidDataSourceproperty nameurl valuejdbc:mysql://localhost:3306/ecommercedb/property nameusername valueroot/property namepassword value123456/property namedriverClassName valuecom.mysql.jdbc.Driver //bean
/beans在主文件中这样写
package com.example.project1;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;import javax.sql.DataSource;public class Project1Application {public static void main(String[] args) {// IoC容器ApplicationContext ctx new ClassPathXmlApplicationContext(applicationContext.xml);DataSource dataSource (DataSource) ctx.getBean(dataSource);System.out.println(dataSource);}}就可以打印出结果
注
要学会查看类中的构造和set方法以选择合适的注入方式。