Spring知识整理(一)Spring知识整理之起步
Spring 是一个开源框架.为简化企业级应用开发而生. 使用 Spring 可以使简单的 JavaBean实现以前只有 EJB 才能实现的功能.
Spring 是一个 IOC(DI) 和 AOP 容器框架.
如下所示,B/S架构图
•具体描述 Spring:
–轻量级:Spring 是非侵入性的 - 基于 Spring 开发的应用中的对象可以不依赖于 Spring 的 API
–依赖注入(DI ---dependency injection、IOC)
–面向切面编程(AOP ---aspect oriented programming)
–容器: Spring 是一个容器, 因为它包含并且管理应用对象的生命周期
–框架: Spring 实现了使用简单的组件配置组合成一个复杂的应用. 在 Spring 中可以使用 XML 和 Java 注解组合这些对象
–一站式:在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上 Spring 自身也提供了展现层的 SpringMVC和 持久层的 SpringJDBC)
(在知识整理过程中,将使用Spring4.0)
来搭建起Spring的框架,使用国际入门HelloWorld
(1.jar包导入)
(2.bean文件)
/** * Created by Administrator on 2018/3/31. */ public class HelloWorld { private String name; public void hello(){ System.out.println("hello,"+name); } public String getName() { return name; } public void setName(String name) { System.out.println("Spring为属性复值"); this.name = name; } public HelloWorld() { System.out.println("Spring开始构造HelloWorld类"); } }
(3.构建Spring的配置文件applicationContex.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: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 -->
<!--class:bean的全类名,通过反射的方式在IOC容器中创建bean,所以要求bean中必须有无参构造函数--> <!--id:创建完成bean之后,通过id来获取bean,id唯一--><bean id="helloWorld" class="HelloWorld"> <!-- 为属性赋值 --> <!--property中的name所对应的属性需要在Class所指定的类中具有set方法--> <property name="name" value="Spring"></property> </bean></beans>
(4.测试框架是否搭建完成)
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by Administrator on 2018/3/31. */ public class Main { public static void main(String[] args){ // 原始 // HelloWorld helloWorld =new HelloWorld(); // helloWorld.setName("spring"); // Spring使用 步骤: // 1.创建Spring的IOC容器对象 ApplicationContext applicationContext =new ClassPathXmlApplicationContext("classpath:spring/applicationContex.xml"); // 2.从IOC容器中获取Bean实例 HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloWorld"); // 3.调用方法 helloWorld.hello(); } }
(5.运行结果)
总结:从搭建到运行我们可以看到,Spring首先是利用反射的技术,构建<bean>标签中的类,然后找到标签<property>name属性对应的实体属性进行赋值