首页 > 其他分享 >Spring5框架-cnblog

Spring5框架-cnblog

时间:2023-08-28 12:13:27浏览次数:34  
标签:xml String 框架 spring void cnblog class public Spring5

Spring5框架

基础

使 用:JavaBean

目 的解决企业应用开发的复杂性

功 能:使用基本的JavaBean代替EJB,本身是一个大杂烩,整合了现有的技术框架

范 围: 任何Java应用

Spring框架以interface21框架为基础,经过重新设计,不断丰富,于2001年发布1.0正式版,轻量级的控制反转(IOC)h和面向切面编程的框架,非入侵式的框架,支持事物,对框架整合的支持

GitHub网址:Search · spring · GitHub

中文文档:https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference

英文文档:Spring Framework Documentation

官方下载地址:https://repo1.maven.org/maven2/org/springframework/spring/

导maven以及jdbc包

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

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

spring范围

image-20210812214433363

spring学习路线

image-20210812214933622

  • spring boot

    • 一个快速开发的脚手架
    • 基于springboot可以快速开发单个微服务
    • 约定大于配置
  • spring Cloud

springcloud是基于springboot开发的,学习SpringBoot的前提,需要完全掌握Spring以及SpringMVC

Ioc理论

控制反转,是一种思想.

控制反转是一种通过描述(xml或者注解)并通过第三去生产或获取特定对象的方式。在spring中实现控制反转的是定义信息直接以注解的形式定义在实现类中,其实现方法是依赖注入(Dependency Injection,DI)

eg:注入set方法

dao类:

public interface UserDao {
    void getUser();
}
public class UserDaoImpl implements UserDao{
    public void getUser(){
        System.out.println("默认获取用户数据");
    }
}
public class UserDaoMysqlImpl implements UserDao{
    public void getUser() {
        System.out.println("获得mysql对象");
    }
}

service类:

public interface UserService {
    void getUser();
}
public class UserServiceImpl implements UserService{
   private UserDao userDao ;
//使用set进行动态实现值的注入
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void getUser() {
      userDao.getUser();
    }
}

测试类:

public class MyTest {


    public static void main(String[] args) {
        //用户实际调用的是业务层,dao层他们不需要接触
        UserServiceImpl userService = new UserServiceImpl();
        userService.getUser();
        //----------------------------------
        //利用set进行动态实现值的注入
        ((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
        userService.getUser();

    }
}

如果不用set方法,测试类每次在service类中访问dao资源时都要在service里面创建一个dao对象,对程序员的依赖性很强,使用set方法后,用户只需要在测试类中建一个dao对象,通过service的set方法直接调用dao资源,释放了程序员的工作,降低了系统的耦合度

image-20210812232458675

hello Spring

配置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">

    <bean id="hello" class="com.dsm.pojo.Hello">
        <!-- collaborators and configuration for this bean go here -->
<!--        一个bean相当于一个对象(new Hello())-->
        <property name="str" value="Spring"></property>
    </bean>


    <!-- more bean definitions go here -->

</beans>

主类:
public class Hello {
    private String str;

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    @Override
    public String toString() {
        return "Hello{" +
                "str='" + str + '\'' +
                '}';
    }
}

测试类

public class MyTest {
    public static void main(String[] args) {
        //获取spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //我们的对象现在都在spring中管理了,我们要使用,直接去里面取出来就可以了
        Hello hello = (Hello)context.getBean("hello");
        System.out.println(hello.toString());
    }
}

控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用spring后对象是由spring控制的

反转:程序本身不创建对象,而被动的接受对象

依赖注入:就是利用set方法进行注入的

IOC是一种编程思想,由主动编程变成被动接受

IOC创建对象方式

无参构造创建(默认)

public User() {
    System.out.println("获取无参构造方法");
}
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    User user = (User)context.getBean("user");
    user.toString();
}

有参构造创建

1.下标赋值创建

配置文件

<bean id="user1" class="com.dsm.pojo.User">
    <constructor-arg index="0" value="谭振飞">
    </constructor-arg>
</bean>

实体类

public User(String name) {
    this.name=name;
}
public void show() {
    System.out.println("name=" + name);
}

测试类

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        User user = (User)context.getBean("user1");
        user.show();
    }
}

2.通过类型创建

不建议使用,可能有重复的类型

配置文件

<bean id="user2" class="com.dsm.pojo.User">
    <constructor-arg type="java.lang.String" value="谭振飞2"/>
</bean>

实体类与测试类与上种方法基本不变

3.通过参数名创建

<bean id="user3" class="com.dsm.pojo.User">
    <constructor-arg name="name" value="谭振飞"/>
</bean>

spring配置

别名(alias)

将user3起别名为user4

<alias name="user3" alias="user4"/>

bean

<bean id="user3" class="com.dsm.pojo.User" name="user4,u4;u5">
    <constructor-arg name="name" value="谭振飞"/>
</bean>

id:bean唯一的标识符,也就是我们所谓的对象名

class:对象对应的全限定名:包名+类型

name:别名,name可以取多个别名

import

一般用于团队开发,可以将多个配置文件合并为一个applicationContext.xml

<import resource="beans1.xml"/>
    <import resource="beans2.xml"/>
    <import resource="beans3.xml"/>
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

DI依赖注入

构造器(有参/无参)注入

前面已经记录

set方式注入(重要)

依赖:bean对象的创建依赖于容器

注入:bean对象的所有属性由容器注入

配置文件:

<?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="address" class="com.dsm.pojo.AddRess">
    <property name="adress" value="郑州"/>
</bean>

<bean id="student" class="com.dsm.pojo.Student">
<!--    第一种普通值注入  value-->
    <property name="name" value="谭振飞"/>
<!--    第二种bean注入  ref-->
    <property name="addRess" ref="address"/>

<!--    数组注入-->
    <property name="books">
        <array>
            <value>平凡世界</value>
            <value>活着</value>
            <value>战争论</value>
        </array>
    </property>
<!--list注入-->
    <property name="hobby">
        <list>
            <value>听歌</value>
            <value>看书</value>
            <value>敲代码</value>
        </list>
    </property>
    <!--        map注入-->
    <property name="card">
        <map>
            <entry key="卡号" value="111111111"></entry>
            <entry key="密码" value="123456"></entry>
        </map>
    </property>
<!--    set注入-->
<property name="games">
    <set>
        <value>雪人兄弟</value>
        <value>魂斗罗</value>
        <value>超级玛丽</value>
    </set>
</property>
<!--    null注入-->
    <property name="wife">
        <null></null>
    </property>
<!--    property注入-->
    <property name="info">
        <props>
            <prop key="url">男</prop>
            <prop key="name">root</prop>
            <prop key="password">123456</prop>
        </props>
    </property>
</bean>

</beans>

实体类

package com.dsm.pojo;

import java.util.*;

public class Student {
    private  String name;
   private AddRess addRess;
   private String[] books;
   private List<String> hobby;
   private Map<String,String> card;
   private Set<String> games;
   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> getHobby() {
        return hobby;
    }

    public void setHobby(List<String> hobby) {
        this.hobby = hobby;
    }

    public Map<String, String> getCard() {
        return card;
    }

    public void setCard(Map<String, String> card) {
        this.card = card;
    }

    public Set<String> getGames() {
        return games;
    }

    public void setGames(Set<String> games) {
        this.games = games;
    }

    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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", addRess=" + addRess.toString() +
                ", books=" + Arrays.toString(books) +
                ", hobby=" + hobby +
                ", card=" + card +
                ", games=" + games +
                ", wife='" + wife + '\'' +
                ", info=" + info +
                '}';
    }
}
package com.dsm.pojo;

public class AddRess {
    private String adress;

    public String getAdress() {
        return adress;
    }

    public void setAdress(String adress) {
        this.adress = adress;
    }

    @Override
    public String toString() {
        return "AddRess{" +
                "adress='" + adress + '\'' +
                '}';
    }
}

测试类:

import com.dsm.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());

    }



}

set注入与构造器注入如何选择

  1. 强制依赖使用构造器进行,使用setter注入有概率不进行注入导致null对象出现
  2. 可选依赖使用setter注入进行,灵活性强
  3. Spring框架倡导使用构造器,第三方框架内部大多数采用构造器注入的形式进行数据初始化,相对严谨
  4. 如果有必要可以两者同时使用,使用构造器注入完成强制依赖的注入,使用setter注入完成可选依赖的注入
  5. 实际开发过程中还要根据实际情况分析,如果受控对象没有提供setter方法就必须使用构造器注入
  6. 自己开发的模块推荐使用setter注入

其他注入方式

p命名空间注入

set方式注入,需要无参构造和set方法

可以直接注入属性的值

image-20210815095828897

c命名空间方式注入

构造器注入,需要有参构造器

image-20210815100318477

注意,不能直接使用p命名和c命名,需要导入xml

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

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

beean的作用域

Scope Description
singleton(单例模式,默认机制) (Default) Scopes a single bean definition to a single object instance for each Spring IoC container.
prototype(原型模式) Scopes a single bean definition to any number of object instances.
request
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.
websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

单例模式(默认)

调用多次同一个类,只会创建一个对象,后续调用该类的方法时候使用的是同个对象

image-20210815101603959

image-20210815101906806

原型模式

调用多次该类会创建不同对象,并使用不同对象调用该方法

image-20210815102432366

image-20210815102308770

其余开发模式只能在web开发中使用

加载properties文件

不加载系统属性
<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER" "/>

加载多个properties文件
<context:praperty-placeholderlocation="jdbc.properties,msg.properties" />

加载所有propertios文件
<context : property-placeholder location="*.preperties" / >

加载properties文件标准格式

从类路径或jar包中搜索并加载properties文件
<context:property-placeholder location="classpath*

标签:xml,String,框架,spring,void,cnblog,class,public,Spring5
From: https://www.cnblogs.com/tanzhenfei/p/17661963.html

相关文章

  • 带你上手基于Pytorch和Transformers的中文NLP训练框架
    本文分享自华为云社区《全套解决方案:基于pytorch、transformers的中文NLP训练框架,支持大模型训练和文本生成,快速上手,海量训练数据》,作者:汀丶。1.简介目标:基于pytorch、transformers做中文领域的nlp开箱即用的训练框架,提供全套的训练、微调模型(包括大模型、文本转向量、文本生......
  • 【Ehcache技术专题】「入门到精通」带你一起从零基础进行分析和开发Ehcache框架的实战
    缓存大小的设置缓存大小的限制可以设置在CacheManager上,也可以设置在单个的Cache上。我们可以设置缓存使用内存的大小,也可以设置缓存使用磁盘的大小,但是使用堆内存的大小是必须设置的,其它可设可不设,默认不设就是无限制。在设置缓存大小的时候,我们可以设置缓存使用某一个存储器的最......
  • GolangWeb框架——Gin框架的使用
    Gin是一个轻量级、灵活和高性能的Web框架,基于Go语言开发。它提供了简洁的API设计和出色的性能,使得构建Web应用程序变得更加简单和高效。本文将介绍如何使用Gin框架来快速构建Web应用程序,并展示其主要特性和用法。本文将介绍关于Gin的基本使用方法,包括基本的请求处理与发送响应。G......
  • 【Ehcache技术专题】「入门到精通」带你一起从零基础进行分析和开发Ehcache框架的实战
    Ehcache的存储方式Ehcache中对于缓存的存储主要有三种方式:分别是堆内存、非堆内存和磁盘。其中非堆内存是针对于企业版Ehcache才有的功能,它可以不受JavaGC的影响,能够创建很大的缓存。堆内存(MemoryStore)我们通常所有的MemoryStore实际上就是堆内存存储。MemoryStore总是可用的,所有......
  • Struts2输入校验以及错误信息处理(2)——用Struts2定义好的校验框架进行校验
    Struts2的输入校验有两种方式:一种是用Action中定义的validate()方法进行校验,一种是用Struts2定义好的校验框架进行校验。前者里面的逻辑判断要自己写,而后者只需要传递相应的参数即可。不管是哪种方式,程序执行的流程都是一样的,执行流程如下:1、对表单传递过来的数据,先进行类型转换......
  • Python 主流RPC 框架有哪些
    PythonRPC框架的使用越来越广泛。在这篇博客中,我将介绍三个主流的PythonRPC框架:gRPC、Thrift和RPyC,并对它们的特点进行比较。 RPC、Thrift和RPyC,并对它们的特点进行比较。框架开发公司序列化格式支持语言文档和社区支持gRPCGoogleProtocolBuffers多种语言,......
  • 【Flask框架知识点总结】
    【一】Flask框架之初识Flask框架引入Flask框架简单使用简单的Flask框架登陆案例wsgirefwerkzeug【二】Flask框架之配置文件Flask框架的配置文件配置方式【三】Flask框架之路由系统路由系统介绍转换器【四】Flask框架之CBVCBV使用CBV源码简析【五】Flask框......
  • 【12.0】Flask框架之flask-script
    【一】Django中的命令【1】引入django中,有命令pythonmanage.pyrunserver:这个命令用于启动Django开发服务器,让我们能够在本地运行我们的应用程序。它会默认在本地的8000端口上启动服务器,我们可以在浏览器中访问http://localhost:8000来查看应用程序。pythonmanage.......
  • 【11.0】Flask框架之信号
    【一】引入Flask框架中的信号基于blinker,其主要就是让开发者可是在flask请求过程中定制一些用户行为【二】安装【1】安装pip3installblinker【2】内置信号request_started=_signals.signal('request-started')#请求到来前执行request_finished=_......
  • 【13.0】sqlalchemy 集成到Flask框架
    【在Flask中集成SQLAlchemy】在Flask中集成SQLAlchemy可以通过使用第三方扩展包flask-sqlalchemy来实现,以下是详细的步骤和说明:首先,需要导入SQLAlchemy类以及flask_sqlalchemy模块:fromflask_sqlalchemyimportSQLAlchemy实例化SQLAlchemy对象:db=SQLAlchemy()这个......