IoC:Inversion of control:控制反转:在传统开发模式下,对象的创建过程和管理过程都是由开发者通过Java程序来实现的,操作权在开发者的Java程序中,当使用了Spring框架后,对象的创建与管理都不再由开发者编写的程序来决定!而是交给框架来决定,具体的做法可以是通过配置框架的XML文件来实现,或其它方式。
DI:Dependency Injection:依赖注入:为类的属性注入值。
IoC是Spring框架所实现的目标,而DI是实现该目标所使用的手段,即:Spring通过DI实现了IoC。
1、注入已有对象:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<!--
bean:被容器所管理的对象
bean标签有两个必要属性:
id:bean的名称,要求唯一,不能冲突
class:要写的类的完整的名字(包名.类名)
注:Spring容器是利用java反射来查找类的字节码文件,然后完成类的加载
Map<String, Object> map = new HashMap<String, Object>();
Class<?> c = Class.forName("first.Apple");
Object a1 = c.newInstance();
map.put("a1", a1);
-->
<!--通过默认空参构造创建bean-->
<bean id="object" class="java.lang.Object"/>
<!--
通过静态工厂方法创建bean
Calendar c = Calendar.getInstance();
factory-method:用来指定一个静态工厂方法。
注:容器会调用该方法来创建对象
-->
<bean id="calendar" class="java.util.Calendar" factory-method="getInstance"/>
<!-- 利用实例工厂方法来创建对象 -->
<!--
factory-bean:指定一个bean的id(其实就是指定一个对象)。
容器会调用该bean的实例方法来创建对象。
-->
<bean id="date1" factory-bean="calendar" factory-method="getTime"/>
</beans>
public class TestCase {
private AbstractApplicationContext app;
@Before
public void before() {
app = new ClassPathXmlApplicationContext("classpath:spring.xml");
}
@After
public void after() {
app.close();
}
@Test
public void test() {
Object obj = app.getBean("object", Object.class);
System.out.println(obj);
Object calendar = app.getBean("calendar", Calendar.class);
System.out.println(calendar);
Object date = app.getBean("date", Date.class);
System.out.println(date);
}
}
2、注入自定义对象:
1)使用set注入,其实set注入就是通过调用set方法注入的。
public class User {
private String name;
private int age;
private String[] arrString;
private int[] arrInt;
private Integer[] arrInteger;
private Set<String> set;
private Map<String, Object> map;
private List<String> list;
private Properties prop;
private Date date;
private Calendar cal;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setArrString(String[] arrString) {
this.arrString = arrString;
}
public void setArrInt(int[] arrInt) {
this.arrInt = arrInt;
}
public void setArrInteger(Integer[] arrInteger) {
this.arrInteger = arrInteger;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public void setList(List<String> list) {
this.list = list;
}
public void setProp(Properties prop) {
this.prop = prop;
}
public void setDate(Date date) {
this.date = date;
}
public void setCal(Calendar cal) {
this.cal = cal;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", arrString=" + Arrays.toString(arrString) +
", arrInt=" + Arrays.toString(arrInt) +
", arrInteger=" + Arrays.toString(arrInteger) +
", set=" + set +
", map=" + map +
", list=" + list +
", prop=" + prop +
", date=" + date +
", cal=" + cal +
'}';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="calendar" class="java.util.Calendar" factory-method="getInstance"/>
<bean id="date" factory-bean="calendar" factory-method="getTime"/>
<bean id="user" class="org.spring.teach.User">
<!--基本类型(包含String)-->
<property name="name" value="zhangsan"/>
<property name="age" value="23"/>
<property name="arrInt">
<!-- 数组类型 -->
<array>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
</array>
</property>
<property name="arrString">
<array>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
<value>hello</value>
</array>
</property>
<property name="arrInteger">
<!-- 数组类型也可以使用list注入 -->
<list>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
</list>
</property>
<property name="map">
<!-- map类型 -->
<map>
<entry key="id" value="1"/>
<entry key="name" value="zhangsan"/>
<entry key="age" value="23"/>
<entry key="date" value-ref="date"/>
</map>
</property>
<property name="set">
<!-- set类型 -->
<set>
<value>zhangsan</value>
<value>lisi</value>
<value>wangwu</value>
<value>zhaoliu</value>
</set>
</property>
<property name="list">
<!-- list类型 -->
<list>
<value>1</value>
<value>2</value>
<value>3</value>
<value>4</value>
<value>hello</value>
</list>
</property>
<property name="prop">
<!--properties类型-->
<props>
<prop key="name">zhangsan</prop>
<prop key="age">age</prop>
<prop key="gender">gender</prop>
</props>
</property>
<!-- 引用类型 -->
<property name="cal" ref="calendar"/>
<property name="date" ref="date"/>
</bean>
</beans>
public class TestCase {
private AbstractApplicationContext app;
@Before
public void before() {
app = new ClassPathXmlApplicationContext("classpath:spring.xml");
}
@After
public void after() {
app.close();
}
@Test
public void test() {
User user = app.getBean("user", User.class);
System.out.println(user);
}
}
一月 24, 2019 10:55:13 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@9e89d68: startup date [Thu Jan 24 22:55:13 CST 2019]; root of context hierarchy
一月 24, 2019 10:55:13 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
User{name='zhangsan', age=23, arrString=[1, 2, 3, 4, hello], arrInt=[1, 2, 3, 4], arrInteger=[1, 2, 3, 4], set=[zhangsan, lisi, wangwu, zhaoliu], map={id=1, name=zhangsan, age=23, date=Thu Jan 24 22:55:14 CST 2019}, list=[1, 2, 3, 4, hello], prop={user=c##root, url=jdbc:oracle:thin:@localhost:1521:orcl, driver=oracle.jdbc.driver.OracleDriver, initSize=1, pwd=c##root, maxSize=3}, date=Thu Jan 24 22:55:14 CST 2019, cal=java.util.GregorianCalendar[time=1548341714228,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=0,WEEK_OF_YEAR=4,WEEK_OF_MONTH=4,DAY_OF_MONTH=24,DAY_OF_YEAR=24,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=55,SECOND=14,MILLISECOND=228,ZONE_OFFSET=28800000,DST_OFFSET=0]}
一月 24, 2019 10:55:14 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@9e89d68: startup date [Thu Jan 24 22:55:13 CST 2019]; root of context hierarchy
Process finished with exit code 0
2)构造方法注入
public class User {
private Phone phone;
public User(Phone phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"phone=" + phone +
'}';
}
}
public class Phone {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<bean id="phone" class="org.spring.teach.Phone"/>
<bean id="user" class="org.spring.teach.User">
<!-- index表示构造器中的参数顺序,从0开始 -->
<constructor-arg index="0" ref="phone"/>
</bean>
</beans>
public class TestCase {
private AbstractApplicationContext app;
@Before
public void before() {
app = new ClassPathXmlApplicationContext("classpath:spring.xml");
}
@After
public void after() {
app.close();
}
@Test
public void test() {
User user = app.getBean("user", User.class);
System.out.println(user);
}
}
一月 24, 2019 10:59:20 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@9e89d68: startup date [Thu Jan 24 22:59:20 CST 2019]; root of context hierarchy
一月 24, 2019 10:59:20 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
User{phone=org.spring.teach.Phone@5b87ed94}
一月 24, 2019 10:59:21 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@9e89d68: startup date [Thu Jan 24 22:59:20 CST 2019]; root of context hierarchy
Process finished with exit code 0