初识Spring
1.Spring是一个支持IOC(Inversion of Control),DI(Dependency Injection),AOP(Aspect Oriented Programming)的一个轻量级框架
- 方便解耦,简化开发
- AOP编程的支持
- 声明式事务的支持
- 方便程序的测试
- 方便继承各种优秀框架
Spring下载
离线包 https://repo.spring.io/libs-release-local/org/springframework/spring/
开发工具 https://spring.io/tools
IOC概念
IOC是一个概念,是一种思想,其实现方式多种多样,当前比较流行的方式是DI
基于XML的DI
applicationContext.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">
XML文件结构
- beans是xml文件的根节点
-
xmlns=http://www.springframework.org/schema/beans xmlns=xml NameSpace 类似于java中的package
-
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi是指xml文件遵守xml规范,xsi全名:xml schema instance
-
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 是指具体用到的schema资源
多配置文件
ApplicationContext加载多文件
new ClassPathXmlApplicationContext("applicationContext.xml","application-service.xml");
引入外部文件
<import resource="application-service.xml"/>
Bean的定义与注册
Spring的配置文件是用于指导Spring工厂进行Bean的生产、依赖关系注入及Bean实例分发的“图纸”,它是一个或多个标准的XML文档
<bean id="food" class="com.msb.Food"></bean>
一个bean只能有一个id,但是可以有多个name作为别名
<alias name="user" alias="my_user_bean" />