Spring练习,使用Properties类型注入方式,注入MySQL数据库连接的基本信息,然后使用JDBC方式连接数据库,模拟执行业务代码后释放资源,最后在控制台输出打印结果。

44 阅读1分钟

在com.mhys.demo.pojo包下创建DataSource类,添加Properties类型属性。

package com.mhys.demo.pojo;

import java.util.Map;

import java.util.Properties;

public class DataSource {

private Map<String, String> map;

private Properties properties;

@Override

public String toString() {

return "DataSource [map=" + map + "]";

}

public Properties getProperties() {

return properties;

}

public void setProperties(Properties properties) {

this.properties = properties;

}

public Map<String, String> getMap() {

return map;

}

public void setMap(Map<String, String> map) {

this.map = map;

}

}

在applicationContext.xml配置文件中注册DataSource类到容器。

com.mysql.jdbc.Driver

jdbc:mysql://locahost:3306/goods

root

123456

在com.mhys.demo.service包下创建JdbcService类,添加DataSource类型属性,声明getConnection()方法和close()方法。

package com.zn.mhys.demo.service;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import com.mhys.demo.pojo.DataSource;

public class JdbcService {

private DataSource dataSource;

public Connection getConnection(){

Connection conn = null;

String url = (String) dataSource.getProperties().get("url");

String username = (String) dataSource.getProperties().get("username");

String password = (String) dataSource.getProperties().get("password");

try {

Class.forName(dataSource.getProperties().getProperty("driverClassName"));

conn = (Connection)DriverManager.getConnection(url, username, password);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

public void close(Connection conn){

if (conn!=null) {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

System.out.println("连接释放成功!");

}

}

}

在applicationContext.xml配置文件中注册JdbcService类到容器。

在com.mhys.demo.test包下创建Test测试类。

package com.zn.mhys.demo.test;

import java.sql.Connection;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.core.io.ClassPathResource;

import com.zn.mhys.demo.service.JdbcService;

public class Test {

public static void main(String[] args) {

ClassPathResource resource = new ClassPathResource("applicationContext.xml");

XmlBeanFactory context = new XmlBeanFactory(resource);

// 2.2.5