Spring概念及Spring程序的简单使用

  • Spring 是一个开源免费的框架(容器)
  • Spring是一个轻量级的,非入侵式的框架
  • 控制反转(IOC),面向切面(AOP)

一句话:Spring就是一个轻量级的控制反转和面向切面的框架。

IOC本质:

控制反转是一种设计思想,DI(dependences in 依赖注入)是实现IOC的以一种方法。
没有IOC的程序中,我们使用面向对象编程,对象的创建与对象之间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,所谓的控制反转即:获得依赖对象的方式反转了。
采用xml方式配置的时候,Beans的定义信息和实现是分离的,而采用注解可以把两者结合在一起,Beans的定义信息直接以注解的方式定义在实现类中,从而达到零配置的目的。

控制反转是一种通过描述(xml或注解)并通过第三方去生产或者获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入。

Spring简单使用:
先添加Spring依赖:

<!--    Spring 依赖-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>

    </dependencies>

存在如下Dao层和业务层:
UserDaoImpl和UserMysqlImpl都实现UserDao接口
在这里插入图片描述

package com.tt.dao;

public interface UserDao {
    void getUser();
}

业务层接口:

package com.tt.service;

public interface UserService {
    void getUser();
}

业务层实现:
在resources目录下编写Beansxml:

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDaoImpl" class="com.tt.dao.UserDaoImpl"/>
    <bean id="mysqlImpl" class="com.tt.dao.UserMysqlImpl"/>

    <bean id="userService" class="com.tt.service.UserServiceImpl">
<!--
                  ref:引用Spring容器中创建好的对象
                  value:具体的值,基本数据类型
-->
        <property name="userDao" ref="mysqlImpl"/>
    </bean>

</beans>

每个标签中的ID 对应的是实现类的实例化对象,class则是对应的实体类路径。
业务层的标签的property属性里,有两个属性:name和ref. 前者指的是实现类的接口。 后者指定的是指向的需要实现的类。

测试:

要使用Spring容器,就要先拿到ApplicationContext对象:

public class MyTest {
    public static void main(String[] args) {
        //获取ApplicationContext对象,拿到Spring容器
       ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml");
        UserServiceImpl userService = (UserServiceImpl)applicationContext.getBean("userService");
        userService.getUser();
    }
}

拿到context对象后,需要什么,就直接从里面get什么。
这里拿到容器里面的userServiceImpl对象,执行里面的getUser()方法,查询出结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值