Spring IoC注入方式详解

Spring IOC依赖注入通常有如下两种方式:

属性注入

IOC容器使用属性的Setter方法来注入被依赖的实例。这种注入方式简单、直观,因而在Spring的依赖注入里大量使用。setter注入实例如下:

//JDBCDataSource.java
public class JDBCDataSource implements Serializable{
    private static final long serialVersionUID = 1L;
    private String driver;
    private String url;
    private String username;
    private String password;
    public String getDriver() {
        return driver;
    }
    public void setDriver(String driver) {
        try{
            Class.forName(driver);
            this.driver = driver;
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public static long getSerialversionuid() {
        return serialVersionUID;
    }
    public Connection getConnection() throws SQLException{
        Connection cn = DriverManager.getConnection(url,username,password);
        return cn;
    }
    public void close(Connection cn){
        if(cn!=null){
            try{
                cn.close();
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }
}
<!-- 配置文件 数据源setter注入 -->
<bean id="dataSource" class="com.spring.dao.JDBCDataSource">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="">123456</property>
</bean>
//testJDBCDataSource.java
@Test
public void testJDBCDataSource() throws SQLException{
	String conf = "applicationContext.xml";
	ApplicationContext ac = new ClassPathXmlApplicationContext(conf);
	JDBCDataSource jds = ac.getBean("dataSource",JDBCDataSource.class);
	Connection cn = jds.getConnection();
	System.out.println(cn);
}

控制台输出:

com.mysql.jdbc.JDBC4Connection@1a7244ca

说明已经获得数据库连接了

利用spring实现JDBCDataSource对象的创建,再使用set注入方式将数据库参数注入给JDBCDataSource,这样就可以正常的调用getConnection()方法获得数据库连接了。

构造注入

IOC容器使用构造器来注入被依赖的实例,构造注入在构造实例时,已经为其完成了依赖关系的初始化。通过构造方法注入Bean的属性值或依赖对象,它保证了Bean实例在实例化后就可以使用,IOC构造注入实例如下:

//car.java
public class Car {
	private String brand;
	private String corp;
	private int price;
	private int maxSpeed;

	public Car(String brand, String corp, int price) {
		this.brand = brand;
		this.corp = corp;
		this.price = price;
	}     
	@Override
	public String toString() {
		return "Car{" +
				"brand='" + brand + '\'' +
				", corp='" + corp + '\'' +
				", price=" + price +
				", maxSpeed=" + maxSpeed +
				'}';
	}
}
<!--通过构造方法来配置bean的属性-->
<bean id="car" class="com.hongkun.spring.beans.Car">
    <constructor-arg value="Audi"></constructor-arg>
    <constructor-arg value="Shanghai"></constructor-arg>
    <constructor-arg value="300000"></constructor-arg>
</bean>
//测试car类
Car car = (Car) ctx.getBean("car");
System.out.println(car);

控制台输出: 

Car{brand=’Audi’, corp=’Shanghai’, price=300000.0, maxSpeed=0}

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。