一.Spring是什么?
1.Spring 是一个开源框架.
2.Spring 为简化企业级应用开发而生. 使用 Spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能..
3.Spring 是一个 IOC(DI) 和 AOP 容器框架.
具体描述Sping:
1.轻量级:Spring是非侵入式的,基于Spring开发的应用中的对象可以不依赖于Spring的API
2.依赖注入:(DI—dependencyinjection,IO)(后面介绍)
3.面向切面编程(AOP---aspect oriented programming)
4.容器:Spring 是一个容器,因为它包含并且管理应用对象的生命周期
4.框架:Spring实现了使用简单的组件配置组合成一个复杂的应用,在Spring中可以使用xml和Java注解组合这些对象
5.一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的SpringMVC和持久层的Spring JDBC)
二.搭建Spring开发环境
(1)把jar包加入到工程的lib文件夹下
(2)Spring的配置文件:一个典型的Spring项目需要创建一个或多个Bean配置文件,这些配置文件用于在Spring IOC容器里配置Bean,Bean的配置文件可以你放在classpath下,也可以放到其他目录下
(3)代码实现:
1.先写一个JavaBean,HelloWorld.java
package com.example.spring.beans;
public class HelloWorld {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void hello(){
System.out.println("hello:"+this.name);
}
}
2.在src目录下创建配置文件applicationContext.xml
每一个 <bean></bean>代表一个对象,id是唯一标识,name代表属性名,value代表属性值,这是属性注入,以后还会再说另外一种注入方式,叫构造注入
<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置bean -->
<bean id="h" class="com.example.spring.beans.HelloWorld">
<property name="name" value="Spring"></property>
</bean><pre name="code" class="java"></beans>
3.编写测试类
package com.example.spring.beans;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext
<span style="font-family: Arial, Helvetica, sans-serif;">public class Main {</span>
public static void main(String[] args) {
// HelloWorld helloWorld=new HelloWorld();
// helloWorld.setName("hello world!");
//创建Spring的IOC容器,作用:调用构造方法进行初始化,并调用set方法为参数赋值
//ApplicationContext 代表IOC容器(是个接口)
//ClassPathXmlApplicationContext:ApplicationContext的子接口
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器中获取Bean
//利用Id定位到IOC容器中的Bean
HelloWorld helloWorld=(HelloWorld)ctx.getBean("h");
System.out.println(helloWorld)
//调用hello方法
helloWorld.hello();
}
}