Spring框架

Spring简介

Spring主要作用是为代码解耦,降低代码间的耦合度。是为了解决企业级开发的复杂度问题。系统开发中,根据功能不同,可将系统中的代码分为主业务逻辑和系统级业务逻辑。也称为“胶水框架”。

主业务逻辑:表示某个系统的某个模块额主要业务逻辑。

系统级业务逻辑(交叉业务逻辑):各模块共用的逻辑。(例如连接数据库。 加载驱动,创建连接、开启事务、具体业务、提交业务、释放连接)。

Spring将代码减低耦合度分为两类(两大特点),Ioc和AOP。

Ioc(控制反转):使得主业务在相互调用过程中,不用再自己维护关系了,即不用自己创建使用的对象了,而是由Spring容器统一管理,自动“注入”。

AOP(面向切面编程):使得系统级服务得到最大的复用,不再由程序员手工将系统级服务“混杂”到主业务逻辑中,而是由Spring部署统一完成“织入”。

简单来说,Spring是Java EE/SE一站式轻量级开源框架。

Spring体系结构

 

 Spring由20多个模块组成,它们分别为数据访问/集成、Web、面向切面编程、应用服务器设备管理、消息发送、核心容器和测试。

数据访问与集成:通过JDBC、ORM(对象关系映射,有Mybatis,Hibernate(已淘汰))等。主要通过ORM框架进行数据访问。

Web层:Websocket、servlet、Web(MVC)、Portlet(完成组件的拼接)

Spring特点

非侵入式:业务逻辑可以从Spring框架快速移植到其他框架。与环境无关。

容器

Ioc:通过容器进行控制完成。依赖注入是目前最优秀的解耦方式,将Spring的Bean通过配置文件相关联。而不是已硬编码方式。

AOP:面向切面编程

第一个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.zck</groupId>
    <artifactId>hello-spring</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.27.RELEASE</version>
        </dependency>
    </dependencies>
</project>

 spring-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-3.0.xsd">

    <bean id="userService" class="com.zck.hello.spring.service.UserServiceIml" />
</beans>

MyTest

package com.zck.hello.spring.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;



public class MyTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHi();
    }
}

UserService.java

package com.zck.hello.spring.service;

public interface UserService {
    public void sayHi();
}

UserSeviceIml.java

package com.zck.hello.spring.service;

public class UserServiceIml implements UserService {
    public void sayHi() {
        System.out.println("Hello Spring");
    }
}

运行结果

 

posted @ 2020-07-06 18:06  一笑任逍遥  阅读(140)  评论(0编辑  收藏  举报