spring loc 是一种编程思想,由主动程序变为被动接收。
案列:编写hello spring
步骤:1.导入相关jar包
commons-logging-1.1.3.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-context-support-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-orm-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
2.编写spring配置文件
案列代码:
</pre>hello.java<pre name="code" class="java">package com.xunifeng.bean;
public class Hello {
private String name;
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("hello:"+name);
}
}
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="com.xunifeng.bean.Hello">
<property name="name" value="spring"></property>
</bean>
</beans>
测试代码:
Test.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//解析beans.xml文件生成管理相应的bean对象
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
Hello hello = (Hello)context.getBean("hello");
hello.show();
}
}
hello 是由spring 容器创建的。hello对象属性是由spring容器来设置的。而这个过程叫做:控制反转(依赖注入)。
控制的内容:指谁来控制对象的创建。传统的的应用程序对象是由程序本身来创建对象。在使用spring后,则用spring 来创建对象。
反转:权限发生的转移。正转是由程序本身来创建对象。反转是指程序本身不去创建,而变为被动的接收。
总结:以前对象是由程序创建对象。使用spring后。程序变为被动的接收spring容器创建好的对象。