ssm-spring入门
Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。 Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。以 IoC(Inverse of Control,控制反转)和 AOP(Aspect Oriented Programming,面向切面编程)为内核。是Spring全家桶(Spring framework、SpringMVC、SpringBoot、Spring Cloud、Spring Data、Spring Security 等)的基础和核心。
初识Spring
从简单工程入手:- 创建实体类:
- resources目录下创建spring配置xml文件:
每个bean代表一个实体,id是别名,class是类全称。<?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 id="student" class="com.zx.demo.spring.beans.Student"/> </beans>
- 测试:
ClassPathXmlApplicationContext: 读取装配spring xml配置文件。@Test public void student() { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); }
运行结果如下:
可以看出在装配完spring xml配置文件后,实体类构造方法就已经创建。
依赖注入:
IOC(控制反转)是spring框架的核心思想之一,而这一思想的重要实现方式是DI(依赖注入),依赖注入原理是使用反射,在上诉的例子上用依赖注入来获取实例:- 修改spring配置文件:beans.xml
这个配置文件中,声明了一个实体对象<bean id="student" class="com.zx.demo.spring.beans.Student"> <property name="id" value="123"/> <property name="name" value="张三"/> </bean>
student
,并对其属性id,name
进行了赋值。- 通过配置文件获取该实例
获取实例的核心方法是:@Test public void student() { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Student student = (Student) context.getBean("student"); System.out.println(student); }
context.getBean("student")
,其原理是BeanFactory通过反射获取。- 查看结果
使用注解
上面介绍了使用配置文件注入对象的方式,接下来看看如何使用注解来注释对象:- 修改spring配置文件:beans.xml
要使用注解,首先要添加注解的支持:<context:annotation-config/>
其次添加扫描包名:<context:component-scan base-package="com.zx.demo.spring.beans"/>
- 在实体上添加注解:
这里用到了两个注解:@Component @Value
,其中Component对应<bean>标签,Value对应<property>标签
整个注解等同于:<bean id="student" class="com.zx.demo.spring.beans.Student"> <property name="id" value="123"/> <property name="name" value="张三"/> </bean>
- 查看结果
和使用配置文件注入得到相同效果。