Hello.java
package com.zhao.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring这些都称为Bean
Hello hello = new Hello();
id = 对象名
class = new 的对象
property 相当于对象中的属性设置一个值
bean = 对象 new Hello();
-->
<bean id="hello" class="com.zhao.pojo.Hello">
<property name="str" value="spring"></property>
</bean>
</beans>
Test
import com.zhao.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在Spring中管理了,我么要使用,直接去里面去出来就可以
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的。
-
反转:程序本身不创建对象,而变成被动的接收对象。
-
依赖注入:就是利用set方法来进行注入的。
-
IOC是一种编程思想,由主动的编程变成被动的接收
到了现在,我们彻底不需要在程序中去改动了,要实现不同的操作,只需要在xml配置文件中进行修改,所谓的IoC,一句话来说就是:对象由Spring来创建,管理,装配!
IOC创建对象的方式
1.默认使用无参构造方法创建对象!
2.假设我们要使用有参构造创建对象。
-
下标赋值(1)
<!--第一种,下标赋值!--> <bean id="User" class="com.zhao.pojo.User"> <constructor-arg index="0" value="赵宇航"></constructor-arg> </bean>
-
类型(2)
<!--第二种,通过类型创建,不建议使用--> <bean id="User" class="com.zhao.pojo.User"> <constructor-arg type="java.lang.String" value="赵宇航"></constructor-arg> </bean>
-
参数名(3)
<!--第三种,直接通过参数名设置--> <bean id="User" class="com.zhao.pojo.User"> <constructor-arg name="name" value="赵宇航"></constructor-arg> </bean>
总结:在配置文件加载的时候,容器中管理的对象就已经实例化了!