Spring了解

简介

  • 代码解耦,企业级开发的复杂度问题:耦合度
  • 系统的代码分:
    • 主业务逻辑
      • 银行业务
      • 保险业务
      • ...
    • 系统级业务逻辑,交叉业务
      • eg.JDBC
        1. 加载驱动
        2. 创建连接
        3. 开启事务
        4. SQL操作
        5. 提交事务
        6. 释放连接
  • 胶水框架
  • 分层的 Java SE/EE full-stack(一站式)轻量级开源框架

Spring将解耦的方式分为两类:

  • IoC - 控制反转

    要使用的对象由Spring容器统一管理
    eg.UserService userService = new UserServiceImpl(); ---->交给Spring来完成

  • AOP - 面向切面编程

    系统级服务得到最大复用

Sprint体系结构

Data Access/Integration

  • Spring JDBC 轻量级实现
  • ORM - 对象关系映射
    • MyBatis
    • Hibernate
  • OXM
  • JMS
  • Transactions

Web

  • WebSocket
  • Servlet
  • Web
  • Portlet - 组件的拼接

AOP

Core Container

  • Beans
  • Core
  • Context
  • SpEL

Test

特点

  • 非侵入式
    • Spring框架的API不会在业务逻辑上出现

Spring与IoC

  • 依赖注入
  • Spring的Bean之间以配置文件的方式组织在一起
  • pojo - 原生Java对象
  • Bean

[实操]hello-Spring

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.funtl</groupId>
    <artifactId>hello-spring</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.17.RELEASE</version>
        </dependency>
    </dependencies>
</project>

硬编码示例

Spring配置文件

  • 配置文件 resources/srping-context.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 id="userService" class="com.funtl.hello.spring.service.impl.UserServiceImpl" />
</beans>
  • 拿到Spring配置 MyTest.java - 控制反转
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHi();
    }
}

猜你喜欢

转载自www.cnblogs.com/hhhqqq/p/12582852.html