Spring
春天 软件行业的春天
spring框架在2002首次推出
spring理念:使现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
Spring就是一个轻量级的控制反转(IOC) 和面向切面编程(AOP)的框架!
具体大家可以官网了解或者百度百科
控制反转IOC
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法
简单介绍一下
本来对象的创建和对象间的依赖关系硬存在于编码程序中,对象的创建由程序自己控制,反转控制之后将对象的创建权分给用户,用户可以根据自己的需要来创建自己想要的对象实现服务
HelloSpring项目创建过程
首先创建一个maven项目
导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
- 首先创建一个包文件夹和一个实体类(位置自己定)
public class 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 );
}
}
在spring里面也要写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 id="hello" class="com.zhang.pojo.Hello">
<property name="name" value="Spring你好"/>
</bean>
</beans>
- 现在前提完成,可以编写测试类
@Test
public void test(){
//解析.xml文件 , 生成管理相应的Bean对象
ApplicationContext context = newClassPathXmlApplicationContext(".xml");
//getBean : 参数即为spring配置文件中bean的id .
Hello hello = (Hello) context.getBean("hello");
hello.show();
}
IOC创建对象
- 使用无参构造创建对象,默认
- 假设我们要使用有参构造创建对象
Bean
id : bean 的唯一标识符,也就是相当于我们学的对象名
class : bean 对象所对应的全限定名 : 包名 + 类型
name :也是别名,而且name 可以同时取多个别名 空格隔开
import
可以将多个配置文件,导入合并为一个
需要它的原因是多人合作项目的时候,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个
map数据类型在bean标签里面是
<entry key value/>
null注入 空值
<null/>
bean的作用域 scope属性
prototype 每次创建一个新的对象
singleton 容器中只有一个对象
request session 在web中使用