第一章 Spring管理第三方bean
1.1 Spring管理druid步骤
-
导入jar包
<!--导入druid的jar包--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version></dependency><!--导入mysql的jar包--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.37</version> <!-- <version>8.0.26</version>--></dependency>
-
编写db.properties配置文件
#key=value db.driverClassName=com.mysql.jdbc.Driver db.url=jdbc:mysql://localhost:3306/db220106 db.username=root db.password=root
-
编写applicationContext.xml相关代码
<!-- 加载外部属性文件db.properties--> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder><!-- 装配数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="${db.driverClassName}"></property><property name="url" value="${db.url}"></property><property name="username" value="${db.username}"></property><property name="password" value="${db.password}"></property> </bean>
-
测试
@Test public void testDruidDataSource() throws Exception{//获取容器对象ApplicationContext ioc =new ClassPathXmlApplicationContext("applicationContext_druid.xml");DruidDataSource dataSource = ioc.getBean("dataSource", DruidDataSource.class);System.out.println("dataSource = " + dataSource);DruidPooledConnection connection = dataSource.getConnection();System.out.println("connection = " + connection);}