Spring创建对象
package IOC; public class Hello { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
配置.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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="Hello" class="IOC.Hello"> <property name="name" value="Spring"></property> </bean> </beans>
实例化容器
package IOC; 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("bean1.xml"); Hello h = (Hello) context.getBean("Hello"); System.out.println(h.toString()); } }
示例结果
控制反转
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后对象是由Spring来创建的.
反转:程序本身不创建对象,而变成被动的接收对象.依赖注入:就是利用set方法来进行注入的.