通过简单案例我们来了解下spring的搭建步骤。
新建一个java项目结构如下:
搭建步骤:
1、导入相关的jar包
commons-logging-1.1.3.jar
spring-aop-4.3.10.RELEASE.jar
spring-aspects-4.3.10.RELEASE.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-context-support-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar
spring-jdbc-4.3.10.RELEASE.jar
spring-orm-4.3.10.RELEASE.jar
spring-tx-4.3.10.RELEASE.jar
spring-web-4.3.10.RELEASE.jar
spring-webmvc-4.3.10.RELEASE.jar
2、编写spring配置文件(名称可以自定义)
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.test.bean.Hello">
<property name="name" value="张三" />
</bean>
</beans>
3、Hello.java
public class Hello {
public Hello() {
System.out.println("hello 被创建");
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("hello,"+name);
}
}
4、测试类Test
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 被创建
hello,张三
示例总结:
Hello对象是由spring容器创建的。Hello对象属性是spring容器来设置的。这个过程就叫控制反转。
1)控制的内容:指谁来控制对象的创建;传统的应用程序对象的创建是由程序本身控制的,使用spring后,是由spring来创建对象。
2)反转:正转指程序来创建对象;反转指程序本身不去创建对象,而变为被动接收的对象
以前对象是由程序本身来创建的,使用spring后,程序变为被动接收spring创建好的对象。