Spring 核心功能:IOC
导入Spring jar包:
spring 例子:
xml配置:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
Hello.java
package spring.beans;
public class Hello {
public String name;
public void setName(String name) {
this.name = name;
}
public void show()
{
System.out.println("hello"+name);
}
}
TestHello.java
package spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import spring.beans.Hello;
public class TestLHello {
public static void main(String[] args) {
// 解析beans.xml对象生成相应对象
ApplicationContext context = new ClassPathXmlApplicationContext(
"beans.xml");
//得到bean标签里面的name属性值为hello
Hello hell0 = (Hello) context.getBean("hello");
hell0.show();
}
}
ClassPathXmlApplicationContext:从类路径的xml配置文件中装入上下文定义
FileSystemXmlApplicationContext:从文件系统中xml配置文件中装入上下文定义
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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean就是java对象,由spring容器创建和管理 -->
<bean name="hello" class="spring.beans.Hello">
<property name="name" value="马化腾"></property>
</bean>
</beans>
运行:
可知没有导入struts.commons.logging包,导入该jar包
重新运行:
步骤:
导入jar包
编写spring配置文件
控制反转(依赖注入)
IOC:是一种编程思想,由主动编程变为被动接收
Hello hell0 = (Hello) context.getBean("hello");hello对象由spring容器来创建
对象属性由spring容器来创建