编程语言
首页 > 编程语言> > java Spring简介

java Spring简介

作者:互联网

Spring是什么

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

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

为什么使用Spring

Spring 框架的主要优点

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执行,查看控制台显示信息:
在这里插入图片描述

标签:PersonDao,personDao,java,容器,Spring,模块,简介,public
来源: https://blog.51cto.com/u_14175378/2759906