Spring从菜鸟到高手(三)依赖注入

Spring中有一个技术叫做依赖注入,而依赖注入又分为【构造函数】注入和【Set】注入,前面我们都看到了依赖注入的好处和方便之处,大家也许要问【Set】注入和【构造函数】注入有什么分别呢?
今天我将一个小例子展示给大家这个例子使用了Spring【构造函数】依赖注入方式,究竟【构造函数】【Set】这两种方法哪种好?要看用在什么地方,如果我们的一个属性要随着类的实例保持不变我们就选择使用构造方法注入,如果我们的一个属性变量在这个类的实例中会有可能改变,那么我们就选择Set 注入。


这个例子主要演示的是通过构造函数来实现注入,因为我们这个类的功能是读取Properties文件的信息,以备后面的模块连接数据库,所以连接数据库的信息是不能改变的,将它通过构造函数注入是一个很好的  这样做的好处是 好我们现在就开始

这个类需要导入这几个包
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


大家注意到这个类的构造方法有一个类型为String的参数负责传递进来一个文件名(相对路径),通过Class类的 getResourceAsStream方法读取并且返回一个InputStream类型的对象,
 InputStreamgetResourceAsStream(String name)
          查找具有给定名称的资源。
 
然后java.util.Properties类的load方法将他读取进属性列表
 voidload(InputStream inStream)
          从输入流中读取属性列表(键和元素对)。



public class PropertiesConfig {

    private Properties properties = null;
   
    public PropertiesConfig(String fileUrl)throws IOException
    {
  
       

        InputStream ips = this.getClass().getResourceAsStream(fileUrl);//通过路径字符串得到一个流
        if(ips == null)//判断路径的正确性,如果错误直接抛出异常,不允许向下进行
        {
             throw new IOException("The fileUrl is nullity !");
        }
        this.properties = new Properties();
        properties.load(ips);//将得到的流读取进属性列表
    }
   
    public Properties getProperties() {
        return properties;
    }
    public void setProperties(Properties properties) {
        this.properties = properties;
    }
   
   
}
 
XML配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" " [url]http://www.springframework.org/dtd/spring-beans.dtd[/url]">
<beans>
 <bean id=" popertiesConfig" class=" cn.incast.PropertiesConfig">
  < constructor-arg>
   <value> db.properties</value>         <!--通过构造函数来注入-->
  </ constructor-arg>
 </bean>
</beans>
db.properties文件的内容
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/itcast
jdbc.user=root
jdba.pass=
可是如果我们的【构造函数】有多个参数我们该怎么办呢?
我们可以使用< constructor-arg>的一个属性【index】

  < constructor-arg  index="1">
   <value> db.properties</value>         <!--通过构造函数来注入-->
  </ constructor-arg>
还可以使用< constructor-arg>的另一个属性【type】
  < constructor-arg  type="java.lang.String">
   <value> db.properties</value>         <!--通过构造函数来注入-->
  </ constructor-arg>
例子1、
<bean id=" popertiesConfig" class=" cn.incast.PropertiesConfig">
  < constructor-arg index="1">
   <value> db.properties</value>         <!--构造函数参数1-->
  </ constructor-arg>
  < constructor-arg index="1">
   <value> db.properties</value>         <!--构造函数参数2-->
  </ constructor-arg>

 </bean>
例子2、

 
<bean id=" popertiesConfig" class=" cn.incast.PropertiesConfig">
  < constructor-arg itypr="java.lang.String">
   <value> db.properties</value>         <!--构造函数参数1-->
  </ constructor-arg>
<!--遇到这种两个参数都是一个类型,并且无法分辨究竟哪个是第一个参数哪个是第二个参数就需要使用index了-->
  < constructor-arg type="java.lang.String">
   <value> db.properties</value>         <!--构造函数参数2-->
  </ constructor-arg>

 </bean>
----------------------------------------------
以下是通过Set注入的例子很简单,相信大家,一看就懂
import java.io. IOException;
import java.sql. Connection;
import java.sql. DriverManager;
import java.sql. ResultSet;
import java.sql. SQLException;
import java.sql. Statement;
import java.util. Properties;
import java.util.logging. Logger;
 
/*
 * 用于通过propertiesConfig文件建立连接
 *
 */
public class ConnectionConfig {
 private PropertiesConfig propertiesConfig = null;
 private Logger log = Logger.getLogger("cn.incast.ConnectionConfig");
 
 public Connection foundConnection()throws IOException,ClassNotFoundException,SQLException
 {
  
  Properties propts = null;
  Connection cn = null;
  
  propts = propertiesConfig.getProperties();
  Class.forName(propts.getProperty("jdbc.driver"));
   cn = DriverManager.getConnection(
     propts.getProperty("jdbc.url"),
     propts.getProperty("jdbc.user"),
     propts.getProperty("jdbc.pass"));
  return cn;  
 }
 
 public void closeConnection(Connection cn)
 {
  if(cn !=null)
  {
   try
   {
    cn.close();
    cn = null;
   }
   catch (SQLException e)
   {log.warning("Connection call on error !");}
  }
 }
 public void closeStatement(Statement stmt)
 {
  if(stmt !=null)
  {
   try
   {
    stmt.close();
    stmt = null;
   }
   catch (SQLException e)
   {log.warning("Statement call on error !");}
  }
 }public void closeResultSet(ResultSet rs)
 {
  if(rs !=null)
  {
   try
   {
    rs.close();
    rs = null;
   }
   catch (SQLException e)
   {log.warning("ResultSet call on error !");}
  }
 }
  public PropertiesConfig getPropertiesConfig() {
  return propertiesConfig;
 }
 public void setPropertiesConfig(PropertiesConfig propertiesConfig) {
  this.propertiesConfig = propertiesConfig;
 }
 
}
这个类是为我下一篇文章作铺垫的,我的下一篇文章是介绍Spring与数据库连接的一些小的心得,主要使用Spring连接数据库其中用到了JaKarta的BasicDtatSource数据源对象、Sql注入攻击以及JDBC调用MySql的存储过程和方法,敬请期待。

本文出自 “绝缘材料” 博客,请务必保留此出处http://tonyaction.blog.51cto.com/227462/42041


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值