Spring是一个容器性质一站式的框架,它可以贯穿三层架构,甚至前端和Python也可能会用到它。它方便解耦、简化开发,提供IoC(Inverse of Control,反转控制)容器(本质就是存放对象的,避免new过多对象)、DI(Dependency Injection,依赖注入)功能和AOP(Aspect Oriented Programming,面向切面编程)功能,简化事务管理,还整合了测试功能。

模块

Spring具有三种使用方式:基于配置文件、基于注解+配置文件、基于注解。其中全注解方式是Spring 5新增的。Spring框架包含多个模块,总结如下:

模块/JAR包 功能
spring-beans 核心容器中的对象
spring-core 核心组件工具类
spring-context 核心容器
spring-expression 核心表达式组件
spring-aop AOP(面向切面编程)组件
spring-aspects AOP组件
aopalliance AOP组件
aspectjweaver AOP组件
spring-test 测试组件
spring-jdbc Java数据库连接组件
spring-tx 数据库事务管理组件

配置文件

基于配置文件,常用的XML头部导入命名空间如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:tx="http://www.springframework.org/schema/tx"
  7. xmlns:p="http://www.springframework.org/schema/p"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop.xsd
  14. http://www.springframework.org/schema/context
  15. http://www.springframework.org/schema/context/spring-context.xsd">
  16. </beans>

注解

  • 配置类注解@Configuration:指明当前类是配置类;@ComponentScan(package):指明当前包或特定位置下的包及子包下的类是Bean类;@Bean:指明将该方法的返回值放入Spring容器中,能够被其它Bean类所依赖;@PropertySource:加载配置文件,可以使用${key}调用文件的value值;@Import:导入其它配置类。
  • Bean(pojo)类注解@Component@Controller@Service@Repository:功能一样,但语义不同,分别指明该类为Bean、Web、Service、Dao层的对象;@Scope:指定Bean类的生命周期,可以为singleton单例、prototype多例、request、session、golbal session;@Value(value):为属性使用Set方法赋值;@Autowaired:根据属性类型从容器调用合适的对象自动赋值;@Qualifier(value):为Autowaired指明一个id,也可以用在方法的参数上;@Resource(name):按照容器内对象的id注入;@PostConstruct:指定该方法在对象初始化时调用;@PostDestroy:指定该方法在对象销毁时调用。