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

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


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

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


大家注意到这个类的构造方法有一个类型为String的参数负责传递进来一个文件名(相对路径),通过Class类的 getResourceAsStream方法读取并且返回一个InputStream类型的对象,
 InputStream getResourceAsStream(String name) 
          查找具有给定名称的资源。
 
然后java.util.Properties类的load方法将他读取进属性列表
 void load(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的存储过程和方法,敬请期待。









本文转自 tony_action 51CTO博客,原文链接:http://blog.51cto.com/tonyaction/42041,如需转载请自行联系原作者
目录
相关文章
|
2月前
|
XML Java 程序员
Spring的依赖注入
Spring的依赖注入
|
4月前
|
XML Java 程序员
Spring基础篇:依赖注入
Spring基础篇:依赖注入
|
4月前
|
Java 容器 Spring
Spring-依赖注入(DI)入门案例及bean基础配置
Spring-依赖注入(DI)入门案例及bean基础配置
42 0
|
4月前
|
XML Java 数据格式
深入理解 Spring IoC 和 DI:掌握控制反转和依赖注入的精髓
在本文中,我们将介绍 IoC(控制反转)和 DI(依赖注入)的概念,以及如何在 Spring 框架中实现它们。
62 0
|
2月前
|
Java Spring
Spring5深入浅出篇:Spring中ioc(控制反转)与DI(依赖注入)
Spring5深入浅出篇:Spring中ioc(控制反转)与DI(依赖注入)
|
3月前
|
Java API Spring
Spring6-IoC(Inversion of Control)控制反转和DI(Dependency Injection)依赖注入,手动实现IOC
Spring6-IoC(Inversion of Control)控制反转和DI(Dependency Injection)依赖注入,手动实现IOC
|
4月前
|
XML Java 数据格式
Spring注解开发管理第三方bean及依赖注入
Spring注解开发管理第三方bean及依赖注入
51 0
|
4月前
|
前端开发 Java API
Spring Boot之Spring MVC基于注解的控制器(RequestMapping注解类型 重定向与转发 依赖注入)
Spring Boot之Spring MVC基于注解的控制器(RequestMapping注解类型 重定向与转发 依赖注入)
43 0
|
1月前
|
Java 数据库连接 API
【Spring】1、Spring 框架的基本使用【读取配置文件、IoC、依赖注入的几种方式、FactoryBean】
【Spring】1、Spring 框架的基本使用【读取配置文件、IoC、依赖注入的几种方式、FactoryBean】
46 0
|
4月前
|
XML Java 数据格式
手写spring 框架——第二篇(依赖注入)
手写spring 框架——第二篇(依赖注入)
41 0