spring学习笔记(上)

简介: spring学习笔记(上)

1.1 简介



    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>


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


1.2,优点


  • spring 是一个开源的免费的框架(容器)
  • spring是一个轻量级的,非侵入式的框架
  • 控制反转(IOC),面向切面编程(AOP)
  • 支持十五处理,对框架整合支持


1.3,spring的组成


The following diagram shows a high-level view of how Spring works. Your application classes are combined with configuration metadata so that, after the ApplicationContext is created and initialized, you have a fully configured and executable system or application.


container-magic.png


1.4,扩展


springboot-1-01.png


  • spring boot
  • 一个快速的开发脚手架
  • 基于Springboot可以快速的开发单个微服务
  • 约定大量配置
  • spring cloud
  • springcloud是基于Springboot实现的


因为现在大多数的公司都在使用Spring Boot进行快速的开发,学习springboot的前提需要掌握spring,springmvc。承上启下。

弊端:发展太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱



1.5 IOC理论(控制反转)


在面向对象的传统方式中,获取对象的方式通常是用new关键字主动创建一个对象。spring中的Ioc方式对象的生命周期有spring框架提供的ioc容器来管理,直接从IoC容器中获取一个对象,控制权从应用程序交给了IoC容器。理论上是借助于“第三方”实现具有依赖关系对象之间的解耦,如下图,即把各个对象类封装之后,通过IoC容器来关联这些对象类。这样对象于对象之间就通过IoC容器进行联系,而对象与对象之间就没有什么联系。


20210308102417164.png

应用程序没有引入IoC容器之前,对象A依赖对象B,那么A对象在实例化或者运行到某一点的时候,自己必须主动创建对象B或者使用已经创建好的对象B,其中无论是创建还是使用自己创建的对象B控制权都在应用程序自身。如果应用程序引入IoC容器之后,对象A和对象B之间失去了直接联系,那么当对象A实例化和运行时,如果需要对象B,IoC容器就会主动创建一个对象B注入(依赖注入)到对象A所需要的地方。由此,对象A获得依赖对象B的过程,由主动行为变成被动行为,即把创建对象交给了IoC容器处理,控制权颠倒了过来,这就是所谓的控制反转。


在之前的业务中,用户的需求可能会影响我们原来的代码,我们需要更具用户的需求区修改原来的代码!如果程序代码量十分巨大,修改一次的成本代价回十分昂贵!


我们可以使用一个set接口实现,已经发生了革命性的变化


    private UserDao userDao;
  //利用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }


之前,程序是主动创建对象!控制权在程序员手中


使用set注入,程序不在具有主动性,而是变成了被动的接受对象!


这种思想从本质上解决了问题,我们程序员不用再去管理对象的创建,系统的耦合性大大降低,可以更加专注在业务逻辑上


注意:事实上依赖注入和控制反转是对同一件事情的不同描述,从某个方面说,就是他们描述的角度不同。依赖注入是从应用程序的角度描述,即应用程序依赖容器创建并注入它所需要的外部资源;而控制反转是从容器的角度描述,即容器控制应用程序,由容器反向的向应用程序注入应用程序所需要的外部资源。外部资源可以是外部文件或对象。


1.6 IoC创建对象的方式


  1. 使用无参构造函数创建对象,默认
  2. 使用有参构造函数创建对象。


下标赋值


    <!-- 第一种赋值,下标赋值 -->
    <bean id="user" class="com.qijian.pojo.User">
        <constructor-arg index="0" value="mahuahong"/>
    </bean>


类型赋值


    <bean id="user" class="com.qijian.pojo.User">
<!--            类型赋值-->
<!--        通过类型创建对象-->
        <constructor-arg type="java.lang.String" value="qijian"/>
    </bean>


通过参数名赋值


    <bean id="user" class="com.qijian.pojo.User">
<!--        通过参数名创建对象-->
        <constructor-arg name="name" value="柒间"/>


总结:在配置文件加载的时候,容器中管理的对象就已经初始化了。



2.1spring配置


别名,如果添加了别名也可以通过别名获取对象


<alias name="user" alias="newname"/>



Bean的配置


    <!--
    id : bean 的唯一标识,也就是相当于对象名
    class : bean 对象所对应的全限定名 : 包+类
    name : 也就是别名 可以同时取多个别名
-->
    <bean id="us" class="com.qijian.pojo.User" name="user,us1"/>


import 一般用于团队开发使用,它可以配置对各配置文件,导入合并为一个


假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册不同的Bean中,我们可以用import将所有的bean.xml合并为一个。只用的时候直接使用总的(applicationContex.xml)即可。


    <import resource="beans.xml"/>
     <import resource="beans1.xml"/>


3 依赖注入

3.1 构造器注入

3.2 Set方式注入【重点】


  • 依赖注入:Set注入!
  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中的所有属性,由容器来注入
  • 【环境的搭建】
  • Address类


public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "Address{" +
                "address='" + address + '\'' +
                '}';
    }
}


Students类


public class Student {
    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String,String> card;
    private Set<String> game;
    private String wife;
    private Properties info;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String[] getBooks() {
        return books;
    }
    public void setBooks(String[] books) {
        this.books = books;
    }
    public List<String> getHobbys() {
        return hobbys;
    }
    public void setHobbys(List<String> hobbys) {
        this.hobbys = hobbys;
    }
    public Map<String, String> getCard() {
        return card;
    }
    public void setCard(Map<String, String> card) {
        this.card = card;
    }
    public Set<String> getGame() {
        return game;
    }
    public void setGame(Set<String> game) {
        this.game = game;
    }
    public String getWife() {
        return wife;
    }
    public void setWife(String wife) {
        this.wife = wife;
    }
    public Properties getInfo() {
        return info;
    }
    public void setInfo(Properties info) {
        this.info = info;
    }
    public Student(){}
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", address=" + address.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobbys=" + hobbys +
                ", card=" + card +
                ", game=" + game +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}


bean.xml配置


    <bean id="address" class="com.qijian.pojo.Address"/>
    <bean id="student" class="com.qijian.pojo.Student">
<!--        普通注入  value-->
        <property name="name" value="qijan"/>
<!--        Beans注入 ref-->
        <property name="address" ref="address"/>
<!--            数组注入  -->
        <property name="books">
            <array>
                <value>think in java</value>
                <value>计算机原理</value>
                <value>SSM从入门到精通</value>
            </array>
        </property>
<!--            list-->
        <property name="hobbys">
            <list>
                <value>写代码</value>
                <value>听歌</value>
            </list>
        </property>
<!--        Map-->
        <property name="card">
            <map>
                <entry key="身份证" value="000000000000"/>
                <entry key="银行卡" value="1111111111"/>
            </map>
        </property>
<!--        Set-->
        <property name="game">
            <set>
                <value>王者荣耀</value>
                <value>刺激战场</value>
            </set>
        </property>
<!--        null-->
        <property name="wife">
            <null/>
        </property>
<!--        properties-->
        <property name="info">
            <props>
                <prop key="Driver">222222</prop>
                <prop key="sex">男</prop>
                <prop key="name">qijian</prop>
                <prop key="pwd">root</prop>
            </props>
        </property>
    </bean>


测试类


import com.qijian.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class mytest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
       Student student = (Student) context.getBean("student");
        System.out.println(student.toString());
        /*输出
        Student{
                name='qijan',
                address=Address{a
                    ddress='null'
                    },
                books=[
                    think in java,
                    计算机原理,
                    SSM从入门到精通
                    ],
                hobbys=[
                    写代码,
                    听歌
                    ],
                card={
                        身份证=000000000000,
                        银行卡=1111111111
                        },
                game=[
                       王者荣耀,
                       刺激战场
                       ],
                wife='null',
                info={
                    name=qijian,
                    Driver=222222,
                    sex=男,
                    pwd=root
                    }
             }
         */
    }
}


3.3,其他方式注入


需要注意的是c名命空间和p名命空间不能直接使用需要导入xml约束


c:

xmlns:c="http://www.springframework.org/schema/c"


p:

xmlns:p="http://www.springframework.org/schema/p"
• 1

User类


package com.qijian.pojo;
public class User {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


p名命空间注入


** The p-namespace lets you use the bean element’s attributes (instead of nested <property/> elements) to describe your property values collaborating beans, or both.


P-namespace **


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"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
        <bean id="user" class="com.qijian.pojo.User"
              p:name="qijian"
              p:age="18"
        />
</beans>


c名命空间注入(通过构造器注入)


Similar to the XML Shortcut with the p-namespace, the c-namespace, introduced in Spring 3.1, allows inlined attributes for configuring the constructor arguments rather then nested constructor-arg elements.


**与 p 名称空间的 XML Shortcut 类似,Spring 3.1中引入的 c 名称空间允许内联属性配置构造函数参数,而不是嵌套的构造函数-arg 元素。 **


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="user" class="com.qijian.pojo.User">
        <constructor-arg name="name" value="柒间"/>
        <constructor-arg name="age" value="19"/>
    </bean>
        //c名命空间注入
    <bean id="user1" class="com.qijian.pojo.User" c:name="qijianc" c:age="18"/>
</beans>


c名命空间注入需要由有参构造函数


*** 注意 ***

Null and Empty String Values


//Spring 将属性和类似属性的空参数视为空字符串。下面的基于 xml 的配置元数据片段将 email 属性设置为空 String 值(“”)。
<bean class="ExampleBean">
    <property name="email" value=""/>
</bean>


上面相当于String email=“”;


//The <null/> element handles null values
<bean class="ExampleBean">
    <property name="email">
        <null/>
    </property>
</bean>


上面的注入等价于String email = null;


相关文章
|
4天前
|
前端开发 Java 数据库
SpringBoot学习
【10月更文挑战第7天】Spring学习
24 9
|
5天前
|
XML Java 数据格式
Spring学习
【10月更文挑战第6天】Spring学习
15 1
|
9天前
|
Java 测试技术 开发者
springboot学习四:Spring Boot profile多环境配置、devtools热部署
这篇文章主要介绍了如何在Spring Boot中进行多环境配置以及如何整合DevTools实现热部署,以提高开发效率。
27 2
|
9天前
|
前端开发 Java 程序员
springboot 学习十五:Spring Boot 优雅的集成Swagger2、Knife4j
这篇文章是关于如何在Spring Boot项目中集成Swagger2和Knife4j来生成和美化API接口文档的详细教程。
25 1
|
9天前
|
Java API Spring
springboot学习七:Spring Boot2.x 拦截器基础入门&实战项目场景实现
这篇文章是关于Spring Boot 2.x中拦截器的入门教程和实战项目场景实现的详细指南。
13 0
springboot学习七:Spring Boot2.x 拦截器基础入门&实战项目场景实现
|
9天前
|
Java API Spring
springboot学习六:Spring Boot2.x 过滤器基础入门&实战项目场景实现
这篇文章是关于Spring Boot 2.x中过滤器的基础知识和实战项目应用的教程。
12 0
springboot学习六:Spring Boot2.x 过滤器基础入门&实战项目场景实现
|
9天前
|
Java 关系型数据库 MySQL
springboot学习五:springboot整合Mybatis 连接 mysql数据库
这篇文章是关于如何使用Spring Boot整合MyBatis来连接MySQL数据库,并进行基本的增删改查操作的教程。
14 0
springboot学习五:springboot整合Mybatis 连接 mysql数据库
|
9天前
|
Java 关系型数据库 MySQL
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
这篇文章是关于如何使用Spring Boot框架通过JdbcTemplate操作MySQL数据库的教程。
11 0
springboot学习四:springboot链接mysql数据库,使用JdbcTemplate 操作mysql
|
9天前
|
Java 测试技术 Spring
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
这篇文章介绍了Spring Boot中配置文件的语法、如何读取配置文件以及如何通过静态工具类读取配置文件。
16 0
springboot学习三:Spring Boot 配置文件语法、静态工具类读取配置文件、静态工具类读取配置文件
|
9天前
|
Java Maven Spring
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)
这篇文章介绍了在IntelliJ IDEA社区版中创建Spring Boot项目的三种方法,特别强调了第三种方法的详细步骤。
30 0
springboot学习一:idea社区版本创建springboot项目的三种方式(第三种为主)