java Spring简介

2021/5/7 22:27:04

本文主要是介绍java Spring简介,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Spring是什么

主流的轻量级的 Java Web 开发框架,是分层的 Java SE/EE full-stack 轻量级开源框架。以 IoC(控制反转)和 AOP(面向切面编程)为内核,用JavaBean取代之前臃肿的 EJB的工作。

服务器端采用三层体系架构,分别为表现层(web)、业务逻辑层(service)、持久层(dao)。

  • 表现层:与 Struts2 框架的整合
  • 业务逻辑层:管理事务和记录日志等
  • 持久层:整合 Hibernate 和 JdbcTemplate 等技术。

为什么使用Spring

Spring 框架的主要优点

  • 简化开发,解耦简单
    所有对象的创建、依赖关系的维护都由 Spring 管理
  • 方便集成
    Spring 内部提供了对各种框架(如 Struts2、Hibernate、MyBatis 等)的直接支持。
  • Java EE API 使用难度降低
    Spring 对 Java EE 开发中非常难用的一些 API(JDBC、JavaMail、远程调用等)提供了封装,使之难度降低。
  • 方便测试
    Spring 支持 JUnit4,方便地测试 Spring 程序。
  • AOP 编程的支持
    提供面向切面编程,实现对程序进行权限拦截和运行监控等功能。
  • 声明式事务的支持
    通过配置就可以完成对事务的管理

Spring结构

Spring体系结构

在这里插入图片描述

模块简介

  1. Data Access/Integration(数据访问/集成)
    有JDBC 模块、ORM 模块、OXM 模块、JMS 模块、Transactions 事务模块

  2. Web 模块
    Web 层包括 Web、Servlet、Struts 和 Portlet 组件

  3. Core Container(核心容器)
    Beans 模块、Core 核心模块、Context 上下文模块、Expression Language 模块

  4. 其他模块
    其他模块有 AOP、Aspects、Instrumentation 以及 Test 模块。

Spring控制反转(IoC)

IoC 思想 : 实例的创建不再由调用者管理,而由 Spring 容器创建。程序代码不再控制程序之间的关系,而是由Spring 容器负责。因此,控制权由程序代码转移到了 Spring 容器中,于是控制权发生了反转。

Spring简单使用

新建一个Spring项目,在src目录下创建com.mengma.ioc包,该包下面创建这个三个类。接着在src目录下创建applicationContext,xml文件。最后确保lib目录下面有那几个jar包。
在这里插入图片描述
相关文件代码:

PersonDao .ajva

package com.mengma.ioc;public interface PersonDao {
    public void add();}

PersonDaoImpl .java

package com.mengma.ioc;public class PersonDaoImpl implements PersonDao {
    @Override
    public void add() {
        System.out.println("代码执行了...");
    }}

FirstTest .java

package com.mengma.ioc;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class FirstTest {
    @Test
    public void test() {
        // 定义Spring配置文件的路径
        String xmlPath = "applicationContext.xml";
        // 初始化Spring容器,加载配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                xmlPath);
        // 通过容器获取personDao实例
        PersonDao personDao = (PersonDao) applicationContext.getBean("personDao");
        // 调用 personDao 的 add ()方法=======相当于通过实例化的对象调用方法
        personDao.add();
    }}

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
    
    
    
    <bean id="personDao" class="com.mengma.ioc.PersonDaoImpl" />
    
   	-->
    beans>

执行效果:
在FirstTest.java文件下用JUnit Test执行,查看控制台显示信息:
在这里插入图片描述



这篇关于java Spring简介的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程