概述:

为了解决企业级开发的复杂度问题

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 可以让主业务逻辑不会应为其他技术问题受到阻碍,例如,主业务数据库的操作,其中数据库的连接,提交commit等操作,就属于交叉业务,如果数据库连接不成功就会受到阻碍,导致主业务进行不下去,耦合度较高;而spring 可以良好的解决这个问题

new User();像这种实例化一个对象的操作不在有程序员操作,有Spring管理(控制反转loC)

Spring 的核心是控制反转(IoC)和面向切面编程(AOP)

非侵入式:

  Spring框架的API不会在业务逻辑上出现;由于业务逻辑没有Spring的API,所以有比Spring框架更好的框架,业务逻辑可以从立刻从Spring迁移到其他框架;

 

 Spring----基础 随笔

Spring 由 20 多个模块组成,它们可以分为数据访问/集成(Data Access/Integration)、Web、面向切面编程(AOP, Aspects)、应用服务器设备管理(Instrumentation)、消息发送(Messaging)、核心容器(Core Container)和测试(Test)。

 

 

 第一个Spring应用程序:

目的:测试控制反转:

如果需要更新这些依赖包的版本,在maven的仓库(repository)中搜索:https://mvnrepository.com/search?q=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.zy</groupId>
    <artifactId>工程8</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.17.RELEASE</version>
        </dependency>
    </dependencies>
</project>

主要增加了 org.springframework:spring-context 依赖(单体引用直接4就可以了)

创建 Spring 配置文件

在 src/main/resources 目录下创建 spring-context.xml 配置文件,从现在开始类的实例化工作交给 Spring 容器管理(IoC),配置文件如下:

<?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.zy.service.impl.UserServiceImpl" />  //UserServiceImpl类自己实现
</beans>
  • <bean />:用于定义一个实例对象。一个实例对应一个 bean 元素。

  • id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。

  • class:指定该 Bean 所属的类,注意这里只能是类,不能是接口。

import com.zy.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) {
        //获取Spring容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        //从Spring容器获取对象
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.test();//调用方法
    }
}

  

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄