IoC简介
The Inversion of Control (IoC) is also known as dependency injection (DI)。
IOC 容器主要实现实例化具体的Bean和动态装配。
一、注入类型
1、setter
<bean id="exampleBean" class="examples.ExampleBean"> <!-- setter injection using the nested <ref/> element --> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <!-- setter injection using the neater 'ref' attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
public void setIntegerProperty(int i) {
this.i = i;
}
}
2、构造方法
package x.y;
public class Foo {
public Foo(Bar bar, Baz baz) {
// ...
}
}
<beans> <bean id="foo" class="x.y.Foo"> <constructor-arg ref="bar"/> <constructor-arg ref="baz"/> </bean> </beans>
Spring不能确定基本类型的初始值,例如:
package examples;
public class ExampleBean {
// No. of years to the calculate the Ultimate Answer
private int years;
// The Answer to Life, the Universe, and Everything
private String ultimateAnswer;
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
Spring容器使用,type属性标识简单类型,如:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
也可使用inex属性标识,如:
<bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean>
3、接口注入
很少使用。
二、bean的属性id与name的区别
name可以使用特殊字符,但id不可以。
三、简单属性的注入
package com.gll.spring.ioc.dao;
import com.gll.spring.ioc.model.User;
import com.gll.spring.ioc.service.UserService;
/**
* Created by Administrator on 2015/4/4.
*/
public class UserDaoImpl implements UserDao {
private int daoId;
private String daoStatus;
@Override
public boolean save(User user) {
return true;
}
public int getDaoId() {
return daoId;
}
public void setDaoId(int daoId) {
this.daoId = daoId;
}
public String getDaoStatus() {
return daoStatus;
}
public void setDaoStatus(String daoStatus) {
this.daoStatus = daoStatus;
}
}
<bean id="userDao" class="com.gll.spring.ioc.dao.UserDaoImpl"> <property name="daoId" value="10"></property> <property name="daoStatus" value="sucess" ></property> </bean>
主要使用spring本身提供的一些bean,例如:
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- results in a setDriverClassName(String) call --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="masterkaoli"/> </bean>