Spring框架的复习IoC部分

Spring框架的复习

IoC容器(控制反转,依赖注入)

主要问题

对象由谁创建?
对象属性如何设置?
控制?
反转?
优点?

解答

  • 对象由Spring容器创建
  • 对象属性通过Spring容器设置
  • 控制的内容:传统的应用程序对象的创建时由程序本身控制的,使用Spring后,由Spring创建
  • 反转的内容:正转时之程序来创建对象,而反转指程序本身不回去创建对象,而变味了被动接收对象
  • 在配置文件中声明对象,你需要的时候给你
  • Ioc是一种编程思想,由主动编程变为被动接收,Ioc

优点

  • 对象由原来的程序主动创建变为了程序接收对象,程序员可以集中于业务的实现
  • 实现了各层之间的解耦,实现分离,告别直接依赖

代码示例

Hello.java

public class Hello {
	private String name;
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void show() {
		// TODO Auto-generated method stub
		System.out.println("Hello:"+name);
	}
}

bean.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" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
			<!-- bean就是Java对象,由Spring创建管理 -->
			<bean name="hello" class="com.ch1.bean.Hello">
				<property name="name" value="张三"></property>
			</bean>
</beans>

Test.java

public class Test {
	public static void main(String[] args) {
		//解析bean.xml文件,生成管理相应的bean对象
		ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
		Hello h=(Hello) ctx.getBean("hello");
		h.show();
	}
}

最终结果

在这里插入图片描述

发布了73 篇原创文章 · 获赞 20 · 访问量 4476

猜你喜欢

转载自blog.csdn.net/lzl980111/article/details/102961281