IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> Spring框架 -> 正文阅读

[Java知识库]Spring框架

Spring框架

spring概念

Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。

Spring解决了开发者在J2EE开发中遇到的许多常见的问题,提供了功能强大IOC、AOP及Web MVC等功能。

Spring可以单独应用于构筑应用程序,也可以和Struts、Webwork、Tapestry等众多Web框架组合使用,并且可以与 Swing等桌面应用程序AP组合。因此, Spring不仅仅能应用于JEE应用程序之中,也可以应用于桌面应用程序以及小应用程序之中。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hN6JGlUi-1647088911713)(D:\dyit\20220226\doc\images\image-20220226143641480.png)]

spring框架的基本架构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-foTrvXKd-1647088911721)(D:\dyit\20220226\doc\images\image-20220226144114885.png)]

Spring的helloworld

创建maven项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eNGdNBvY-1647088911723)(D:\dyit\20220226\doc\images\image-20220226144450711.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-duaO51HU-1647088911724)(D:\dyit\20220226\doc\images\image-20220226144531005.png)]

引入spring框架

<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.dyit.spring</groupId>
	<artifactId>spring-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.3.15</version>
		</dependency>
	</dependencies>
</project>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rAxSLGad-1647088911724)(D:\dyit\20220226\doc\images\image-20220226145332165.png)]

定义一个类

package com.dyit.spring;

public class Car {

	private Integer id;
	private String brand;
	private String color;
	private Double price;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Car [id=" + id + ", brand=" + brand + ", color=" + color + ", price=" + price + "]";
	}

}

配置spring容器

<?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="bwmx" class="com.dyit.spring.Car">
		<property name="id" value="1"/>
		<property name="brand" value="奔驰"/>
		<property name="color" value="黄色"/>
		<property name="price" value="800000.00"/>
		
	</bean>

</beans>

实现

//获取容器
		ApplicationContext  act =
				new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");
		
		Car bean = act.getBean(Car.class, "bwmx");
		
		System.out.println(bean);

spring的容器(bean)配置文件

Spring bean的加载流程

Bean配置信息定义了Bean的实现及依赖关系,Spring容器根据各种形式的Bean配置信息在容器内部建立Bean定义注册表,然后根据注册表加载、实例化Bean,并建立Bean和Bean的依赖关系,最后将这些准备就绪的Bean放到Bean缓存池中,以供外层的应用程序进行调用。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-J3MnZ73M-1647088911725)(D:\dyit\20220226\doc\images\image-20220226154802453.png)]

  • 配置bean

    	<bean id="bwmx" class="com.dyit.spring.Car">
    		<property name="id" value="1"/>
    		<property name="brand" value="奔驰"/>
    		<property name="color" value="黄色"/>
    		<property name="price" value="800000.00"/>
    		
    	</bean>
    
  • 容器启动(加载工厂)

    //获取容器
    ApplicationContext  act =
    				new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");	
    
  • 读取配置信息

    在容器中定义了一个bean的注册表: 将Bean的信息注册到容器中

  • 根据注册表实例化Bean的对象

  • 放入容器(工厂)的缓存中

    	Car bean = act.getBean(Car.class, "bwmx");//从缓存中读取
    

bean的配置

bean对象默认是单例的

bean标签

  • id/name : 在容器中的唯一名称(不能重复)

  • class : 类的全名- 包名.类名

  • init-method: 在对象创建之后,第一个调用的方法.

    <bean id="bwmx" class="com.dyit.spring.Car" init-method="initx">
    
  • destroy-method: 在容器销毁对象时调用的方法

    <bean id="bwmx" class="com.dyit.spring.Car" init-method="initx" destroy-method="finish"> 
    
  • ref

    引用容器中的bean的id/name

    public class Person {
    
    	private String name;
    	private Car car;
    
    
    	<bean id="bwmx" class="com.dyit.spring.Car" init-method="initx" destroy-method="finish" > 
    		<property name="id" value="1"/>
    		<property name="brand" value="奔驰"/>
    		<property name="color" value="黄色"/>
    		<property name="price" value="800000.00"/>
    	</bean>
    	
    	<bean id="tom" class="com.dyit.spring.Person">
    		<property name="name"  value="关羽"/>
    		<property name="car" ref="bwmx"/>
    	</bean>
    

    测试: 公司类Company(name, emp) -->员工Emp(name, book) -->Book(title, author,price)

    public class Book {
    
    	private String title;
    	private String author;
    	private double price;
    
    	public String getTitle() {
    		return title;
    	}
    
    	public void setTitle(String title) {
    		this.title = title;
    	}
    
    	public String getAuthor() {
    		return author;
    	}
    
    	public void setAuthor(String author) {
    		this.author = author;
    	}
    
    	public double getPrice() {
    		return price;
    	}
    
    	public void setPrice(double price) {
    		this.price = price;
    	}
    
    	@Override
    	public String toString() {
    		return "Book [title=" + title + ", author=" + author + ", price=" + price + "]";
    	}
    	
    }
    
    public class Emp {
    
    	private String name;
    	private List<Book> books;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public List<Book> getBooks() {
    		return books;
    	}
    	public void setBooks(List<Book> books) {
    		this.books = books;
    	}
    	@Override
    	public String toString() {
    		return "Emp [name=" + name + ", books=" + books + "]";
    	}
    }
    
    
    public class Company {
    
    	private String name;
    	private Map<String, Emp> map;
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public Map<String, Emp> getMap() {
    		return map;
    	}
    
    	public void setMap(Map<String, Emp> map) {
    		this.map = map;
    	}
    
    	@Override
    	public String toString() {
    		return "Company [name=" + name + ", map=" + map + "]";
    	}
    
    }
    
    	<bean id="bookx" class="com.dyit.spring.Book">
    		<property name="title" value="三国演义"/>
    		<property name="author" value="罗贯中"/>
    		<property name="price" value="35.00"/>
    	</bean>
    	
    	<bean id="empx" class="com.dyit.spring.Emp">
    		<property name="name" value="张三"/>
    		<property name="books">
    			<list>
    				<ref bean="bookx"/>
    				<ref bean="bookx"/>
    				<ref bean="bookx"/>
    				<ref bean="bookx"/>
    			</list>
    		</property>
    	</bean>
    	
    	<bean id="comx" class="com.dyit.spring.Company">
    		<property name="name" value="dyit"/>
    		<property name="map" >
    			<map>
    				<entry key="张三" value-ref="empx"/>
    				<entry key="李四" value-ref="empx"/>
    				<entry key="王五" value-ref="empx"/>
    			</map>
    		
    		</property>
    	</bean>
    

    使用注解配置

    @Controller

    @Service

    @Repository

    @Component --组件

    能被<context:component-scan base-package=“com.dyit.spring”/>

    扫描包下的类是否有@Controller, @Service @Repository @Component,将注解的类注册,实例化放入缓存

<?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:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">


	<context:component-scan base-package="com.dyit.spring"/>

</beans>
public interface IBookService {
	
	void deleteBook(int id);

}

@Service
public class BookServiceImpl implements IBookService {

	@Override
	public void deleteBook(int id) {
		System.out.println("删除"+id+"成功");
		
	}
}

@Controller
public class BookController {
    
    //@Autowired :自动查找容器中是否有IBookSerivce这种类型的对象,如果有则注入对象
	@Autowired
	private IBookService ibs; //ibs = new 。。。。
	
	public void del() {
	
		ibs.deleteBook(1);
	}

}
	@Test
	public void testController() {
		ApplicationContext act = new FileSystemXmlApplicationContext("classpath:spring/applicationContext.xml");
		
		BookController bean = act.getBean(BookController.class);
		
		bean.del();
	}

Spring的loC容器

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z1R48Ceq-1647088911727)(D:\dyit\20220227\doc\images\container-magic.png)]

Spring 容器是 Spring 框架的核心。容器将创建对象,把它们连接在一起,配置它们,并管理他们的整个生命周期从创建到销毁。

IOC 容器具有依赖注入功能的容器,它可以创建对象,IOC 容器负责实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。通常new一个实例,控制权由程序员控制,而"控制反转"是指new实例工作不由程序员来做而是交给Spring容器来做。

Spring IoC容器–工厂—》工厂模式

POJO(对象)

配置(xml、注解)—> 解析—>POJO—> IoC—>从IoC获取对象

IOC的概念

IoC: Inverse Of Control 控制反转

  • 工厂中创建了对象,放入缓存中

  • 之前的方式: 需要对象 act.getBean(“对象的id”)—>对象

  • 工厂(IoC):

    A —>B

    a(){ new B()}:控制器在A,A创建B对象

    a(){factory.create()} :控制权转移,造出B对象 a主动通知工厂

    A{

    private B b ;

    }

    IoC容器含义B对象, 发现A需要B的对象,将B的对象注入给A

好莱坞原则:演员–》导演–》简历

你们不用找我,你们的信息我都有,当我需要演员时候,我会主动找你。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W4J6b3Sp-1647088911728)(D:\dyit\20220227\doc\images\image-20220227095448627.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AyE2AyHw-1647088911728)(D:\dyit\20220227\doc\images\image-20220227095510318.png)]

DI是什么?

实现过程中,很复杂,很难实现。 有些概念没有交代的特别请求。

Thoughsworks—>Martin Flower– >微服务

控制权是什么?

如何反转?反转什么?

实现过程中DI: 依赖注入

set注入(推荐)

<bean id="pb" class="com.dyit.entity.Publisher">

	<property name="id" value="1"/>
	<property name="name" value="工人出版社"/>
	<property name="loc" value="长安区"/>
</bean>

构造方法注入

public class Author {
	
	private Integer id;
	private String name;
	private String address;
	
	public Author() {
	}
	
	public Author(String name, String address) {
		this.name = name;
		this.address = address;
	}

	@Override
	public String toString() {
		return "Author [id=" + id + ", name=" + name + ", address=" + address + "]";
	}

}

<bean id="au" class="com.dyit.entity.Author">
  <constructor-arg name="name" value="张三"/>
  <constructor-arg name="address" value="西安"/>
</bean>

接口注入(少)

springmvc框架

spirngmvc框架是对servlet的封装

MVC: struts2 、 springmvc

SSH(组合), SSM(Spring)

springmvc-helloworld

maven项目(javaee)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z77jti1o-1647088911729)(D:\dyit\20220227\doc\images\image-20220227103113058.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AJcFIFSb-1647088911730)(D:\dyit\20220227\doc\images\image-20220227103200686.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tx6hfyST-1647088911731)(D:\dyit\20220227\doc\images\image-20220227103230626.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OjLfxSOK-1647088911732)(D:\dyit\20220227\doc\images\image-20220227103300209.png)]

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
   version="3.1">
  <display-name>springmvc-hello</display-name>

</web-app>

引入springmvc框架

<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.dyit.spring</groupId>
	<artifactId>springmvc-hello</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<!--定义引入依赖的版本号-->
	<properties>
		<project.spring.version>5.3.16</project.spring.version>
		<project.log.version>1.2.17</project.log.version>
		<project.lombok.version>1.18.22</project.lombok.version>
		<project.json.version>2.13.1</project.json.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${project.spring.version}</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${project.log.version}</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>${project.lombok.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${project.json.version}</version>
		</dependency>
	</dependencies>
</project>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GBHBVTO3-1647088911733)(D:\dyit\20220227\doc\images\image-20220227105104682.png)]

完成Controller层的代码

@Controller
public class PublisherController {

	@GetMapping("/findAll")
	@ResponseBody
	public HttpResp findAll() {
		
		List<Publisher> list = new ArrayList<Publisher>();
		list.add(new Publisher(1, "工人出版社",  "西安"));
		list.add(new Publisher(2, "神话出版社",  "北京"));
		list.add(new Publisher(3, "少儿出版社",  "上海"));
		
		HttpResp dto = new HttpResp(20001, "查询所有出版社成功",list, new Date());
		return dto;	
	}
}

配置springmvc框架

配置IoC容器(mvc 容器)
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

	<context:component-scan base-package="com.dyit.controller"/>
	<mvc:resources location="static/" mapping="static/**"/><!-- 不处理静态资源 -->
	<mvc:annotation-driven/>
	
</beans>

配置servlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
   version="3.1">
  <display-name>springmvc-hello</display-name>
  
 <servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springmvc-*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cqfsmGJs-1647088911734)(D:\dyit\20220227\doc\images\image-20220227112932898.png)]

SSM框架整合

SSM整合:

S: SpringMVC

S: Spring

M: Mybatis

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ADHeCtEv-1647088911735)(D:\dyit\20220227\doc\images\image-20220227152729977.png)]

两个IoC容器

  • MVC容器

    管理MVC相关来的对象

    springmvc-serlvet.xml

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Tf81dCOg-1647088911736)(D:\dyit\20220227\doc\images\image-20220227141049084.png)]

    SpringMVC+JSON

    DispatcherServlet类: Servlet

  • 业务容器

    后台业务交互: service 、 mapper/dao 等

    spring-mybatis.xml

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-otcvOTOk-1647088911737)(D:\dyit\20220227\doc\images\image-20220227141222640.png)]

    Spring+mybatis

    监听器: SevletContextListener

  • 日志+lombok等

创建maven(javaee)项目

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jRo9DTgj-1647088911740)(D:\dyit\20220227\doc\images\image-20220227141901748.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RoRLwQWo-1647088911741)(D:\dyit\20220227\doc\images\image-20220227141926599.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gkVdEPF0-1647088911741)(D:\dyit\20220227\doc\images\image-20220227142011210.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2szjC8q4-1647088911742)(D:\dyit\20220227\doc\images\image-20220227142038136.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LI65Jt0P-1647088911742)(D:\dyit\20220227\doc\images\image-20220227142104488.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WG8a444a-1647088911743)(D:\dyit\20220227\doc\images\image-20220227142131047.png)]

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>ssm-base</display-name>

</web-app>

引用maven依赖

相关依赖

  • springwebmvc
  • jackson
  • spring-orm
  • mybatis-spring
  • mybatis
  • druid
  • mysql
  • spring-test
  • junit
  • slf4j-log4j12
  • lombok

POM配置

<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.dyit.ssm</groupId>
	<artifactId>ssm-base</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.spring.version>5.3.16</project.spring.version>
		<project.lombok.version>1.18.12</project.lombok.version>
		<project.json.version>2.13.1</project.json.version>
		<project.mysql.version>8.0.28</project.mysql.version>
		<project.druid.version>1.2.8</project.druid.version>
		<project.mybatis.version>3.5.9</project.mybatis.version>
		<project.mybatis-spring.version>2.0.7</project.mybatis-spring.version>
		<project.junit.version>4.12</project.junit.version>
		<project.log.version>1.7.5</project.log.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${project.spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${project.spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${project.spring.version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${project.mysql.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${project.druid.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${project.mybatis-spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${project.mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${project.junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${project.log.version}</version>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>${project.lombok.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>${project.json.version}</version>	
		</dependency>
	</dependencies>
</project>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rmHuRZ1z-1647088911744)(D:\dyit\20220227\doc\images\image-20220227152615656.png)]

SSM框架配置(结构)

结构

  • log4j.properties
  • web.xml
  • 配置两个容器

配置

  • log4j.properties

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9976WSz9-1647088911744)(D:\dyit\20220227\doc\images\image-20220227150625839.png)]

  • spring的容器

    • mvc容器

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fyUBInbJ-1647088911745)(D:\dyit\20220227\doc\images\image-20220227150726250.png)]

    • 业务容器

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OasB29dL-1647088911745)(D:\dyit\20220227\doc\images\image-20220227150809761.png)]

      druid.driver = com.mysql.cj.jdbc.Driver
      druid.url = jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
      druid.username=root
      druid.password=1234
      
    • web.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      	xmlns="http://java.sun.com/xml/ns/javaee"
      	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
      	version="3.1">
      	<display-name>ssm-base</display-name>
      	<context-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>classpath:spring/mybatis/spring-*.xml</param-value>
      	</context-param>
      	<listener>
      		<listener-class>
      		org.springframework.web.context.ContextLoaderListener
      		</listener-class>
      	</listener>
      	<servlet>
      		<servlet-name>springDispatcherServlet</servlet-name>
      		<servlet-class>org.springframework.web.servlet.DispatcherServlet
      		</servlet-class>
      		<init-param>
      			<param-name>contextConfigLocation</param-name>
      			<param-value>classpath:spring/mvc/springmvc-*.xml</param-value>
      		</init-param>
      		<load-on-startup>1</load-on-startup>
      	</servlet>
      	<servlet-mapping>
      		<servlet-name>springDispatcherServlet</servlet-name>
      		<url-pattern>/*</url-pattern>
      	</servlet-mapping>
      </web-app>
      

项目结构(包+前端)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xHYoPsOv-1647088911746)(D:\dyit\20220227\doc\images\image-20220227154645411.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-74FjUFWM-1647088911747)(D:\dyit\20220227\doc\images\image-20220227154659878.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UM0KyN2g-1647088911747)(D:\dyit\20220227\doc\images\image-20220227154735292.png)]

配置mvc容器

<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

	<context:component-scan base-package="com.dyit.ssm.controller"/>
	<mvc:resources location="static/" mapping="static/**"/>
	<mvc:annotation-driven/>

</beans>

配置业务容器

扫描类创建对象放入容器

@Service @Repository @Component

	<context:component-scan base-package="com.dyit.ssm">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

读取数源的配置信息、配置数据源

<context:property-placeholder location="classpath:spring/mybatis/druid/druid.properties"/>

<bean id="druid" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="url" value="${druid.url}"/>
    <property name="username" value="${druid.usename}"/>
    <property name="password" value="${druid.password}"/>
    <property name="driverClassName" value="${druid.driver}"/>
</bean>

配置SqlSessionFactory

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="druid"/>
		<property name="typeAliasesPackage" value="com.dyit.ssm.entity"/>
		<property name="mapperLocations" value="classpath:spring/mybatis/mapper/*.mapper.xml"/>
	</bean>

配置mybatis的辅助

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.dyit.ssm.mapper"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

事务配置

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="druid"/>
</bean>

<tx:annotation-driven transaction-manager="txManager"/>

实体类

@Alias("Publisher")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Publisher {
	
	private Integer id;
	private String name;
	private String loc;

}

mapper接口

public interface IPublisherMapper {
	
	List<Publisher> findAll();

}

mapper配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC
"-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.dyit.ssm.mapper.IPublisherMapper"><!-- 接口的位置 -->

	<resultMap type="Publisher" id="PublisherMap">
		<id property="id" column="publisher_id"/>
		<result property="name" column="publisher_name"/>
		<result property="loc" column="publisher_loc"/>
	
	</resultMap>


	<select id="findAll" resultMap="PublisherMap">
		SELECT  * FROM publisher_tab
	</select>
	

</mapper>

service

public interface IPublisherService {
	
	List<Publisher> findAll();

}

@Service
@Transactional
public class PublisherServiceImpl implements IPublisherService {
	@Autowired
	private IPublisherMapper mapper;

	@Override
	public List<Publisher> findAll() {
		
		return mapper.findAll();
	}

}

测试servicce

@ContextConfiguration(locations = "classpath:spring/mybatis/spring-mybatis.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestPublisherService {
	
	@Autowired
	private IPublisherService ips;

	@Test
	public void test() {
		System.out.println(ips.findAll());
	}

}

Controller

@Controller
public class PublisherController {
	
	@Autowired
	private IPublisherService ips;
	
	@GetMapping("/findAllPublisher")
	@ResponseBody
	public HttpResp findAllPublisher() {
		return new HttpResp(20001, "测试", ips.findAll());
	}

}

Restfull 幂等性判定:多次对服务器操作不改变服务器状态的。

GetMapping, get方式查询

PUT : Book (id=10)–>后台

PUT 、DELETE、GET – 幂等的

POST -非幂等的

@Autowired@Resource
spring框架注解javax.annotation.Resource;
默认按照类型注入默认使用bean的名称注入
/**
 * @RestController:
 * 类上@RequestMapping("/book"),做命名空间 ,前缀/book, 类似于package概念
 */
@RestController
@RequestMapping("/book")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}

和前端交互

跨域问题

前端访问后台,同一个域

http://ip:port/ssm-web一致

https://ip:port(x)

http://ip:port/ssm-update (x)

前后端分离—>页面 和后台 不同域

Spring AOP

AOP: 面向切面的开发

AOP概念

面向对象:继承

继承: 软件复用(代码复用),

A类 a()方法, B extends A

问题升级

class A{
   
   public void a(){
     before();
       语句1
     after();
   }
   
     public void b(){
       before();
       语句2
       after();
   }
    
    private void before(){
        {
            //代码块1
        }
    }
    
      private void after(){
          {
             // 代码块2
          }
    }

}

问题

方法中出现重复代码,如何复用

AOP思想

面向切面(多个方法方法)的开发

class A{
   
   public void a(){
     
       语句1
   
   }
   
     public void b(){
     
       语句2
     
   }
    
}

class Aop{
    
     public void before(){
        {
            //代码块1
        }
    }
    
      public void after(){
          {
             // 代码块2
          }
    }
}

AOP的实现原理-代理模式

小明准备租三室一厅的房子上班,找访问中介租房,访问中介将房东的房子租给小明。

房东: real

中介:代理

静态代理

public interface IRent {
	void rent();
}
public class HouseKeeper implements IRent {

	@Override
	public void rent() {
		System.out.println("出租豪华三室一厅");
	}
}

public class HouseAgent implements IRent {
	private IRent real;	
	public HouseAgent(IRent real) {
		this.real = real;
	}
	@Override
	public void rent() {
		this.real.rent();
	}
}

@Test
public void test() {
    IRent real = new HouseKeeper();
    IRent agent = new HouseAgent(real);
    agent.rent();

}

优点: 隐藏真实对象(Real)

代理对象的方法进行功能添加修改

缺点: 接口不可变的

动态代理

JDK已经实现了动态代理,接口变更之后,切入可以更加接口方法变化切入。

public interface IRent {	
	void rent();
	void job();
	void c();
}
public class HouseKeeper implements IRent {
	@Override
	public void rent() {
		System.out.println("出租豪华三室一厅");
	}
	@Override
	public void job() {
		System.out.println("找工作");	
	}
	@Override
	public void c() {
		System.out.println("C");		
	}
}

public class AgentMaker implements InvocationHandler {
	
	private Object real; //传入的真实对象
	
	 public AgentMaker(IRent real) {
		this.real = real;
	}
	 /**
	  * 产生代理对象
	  * @return
	  */
	 public IRent createAgent() {
		 
		 return (IRent) Proxy.newProxyInstance(real.getClass().getClassLoader(),
				 real.getClass().getInterfaces(), this);
	 }

	 /**
	  * 调用真实对象的方法
	  */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		before();
		Object retVal = method.invoke(this.real, args);
		after();
		return retVal;
	}

	
	private void before() {
		System.out.println("收取2500押金");
	}
	
	private void after() {
		System.out.println("每月检查卫生一次,不合格罚款100元");
	}

}
	@Test
	public void test() {
		HouseKeeper real = new HouseKeeper();
		IRent r = new AgentMaker(real).createAgent();
	
		r.c();
		
	}


cglib代理

动态代理问题:如果真实对象没有实现任何接口

继承机制:子类继承父类的方法:覆盖

package com.dyit.service.impl;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class AgentMaker implements MethodInterceptor {
	
	private Object real;
	
	public AgentMaker(Object real) {
		this.real = real;
	}
	
	public Object createProxy() {
		Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(real.getClass());
		enhancer.setCallback(this);
		return enhancer.create();
	}
	
	private void before() {
		System.out.println("收取2500押金");
	}
	
	private void after() {
		System.out.println("每月检查卫生一次,不合格罚款100元");
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		before();
		Object retVal =proxy.invokeSuper(obj, args);
		after();
		return retVal;
	}

}

spring aop

aop的相关概念

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SBUWtJRs-1647088911749)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220309192824377.png)]

  • 目标对象(target): 要进行操作的对象
  • 切面(Aspect): 要插入(切入、注入)的代码的业务逻辑
  • 连接点(JoinPoint):连接的方法(其中的一个方法)
  • 切点:多个方法(定义规则)

advise(增强)

  • Before
  • After
  • Around
  • AfterReturning
  • Excetpion

aop实例

  • 建立切面

    @Aspect
    @Service
    public class BookServiceAop {
    
    	@Around("execution(* com.dyit.ssm.service.impl.*.*(..))")
    	public Object testAround(ProceedingJoinPoint pjp) throws Throwable {
    		System.out.println("准备切方法:" + pjp.getSignature());
    		Object retVal = pjp.proceed();// 目标对象执行的方法
    		System.out.println("切入完成:,准备离开......");
    
    		return null;
    	}
    
    }
    
    
  • 增强方式(advise)

    @Around:环绕切

  • 切点: 规则

    execution(* 包 . * . *books(String))

  • 代码

  • 配置

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l8cMEzRN-1647088911749)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220309201340837.png)]

    	<aop:aspectj-autoproxy/>
    

spring的事务管理

事务的隔离级别

脏读: B读取A事务中没提交的数据

不可重复读

幻读

  • READ_UNCOMMITED
  • READ_CMMMITED
  • REPEATABLE_COMMITED
  • SERILIAZABLE

springBoot

springboot概念

The primary goals of Spring Boot are:
To provide a radically faster and widely accessible ‘getting started’ experience for all Spring development.
To be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
To provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
Spring Boot does not generate code and there is absolutely no requirement for XML configuration.

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

springboot的第一个程序

maven项目

在这里插入图片描述

配置maven环境
在这里插入图片描述

引用依赖

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GCoImCp5-1647088911752)(D:\dyit\20220312\笔记\images\image-20220312094642384.png)]

引入<parent>

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.10</version>
 </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
    </dependencies>

项目配置

src–>resources–>config–>application.yml

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n1Ms9PAs-1647088911753)(D:\dyit\20220312\笔记\images\image-20220312103042791.png)]

server:
  port: 8099

springboot的启动类

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class);
    }
}

注意:Main类要在其它类的上一级

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nt2evW7k-1647088911754)(D:\dyit\20220312\笔记\images\image-20220312103248668.png)]

Controller

package com.dyit.controller;

import com.dyit.dto.HttpResp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public HttpResp hello(){
        return new HttpResp(20001,"测试hello",null);
    }
}

运行

"C:\Program Files\Java\jdk1.8.0_311\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2021.3.2\lib\idea_rt.jar=64267:C:\Program Files\JetBrains\IntelliJ IDEA 2021.3.2\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_311\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_311\jre\lib\rt.jar;D:\idea-workspace\springboot-hello\target\classes;C:\maven-repository\org\springframework\boot\spring-boot-starter-web\2.5.10\spring-boot-starter-web-2.5.10.jar;C:\maven-repository\org\springframework\boot\spring-boot-starter\2.5.10\spring-boot-starter-2.5.10.jar;C:\maven-repository\org\springframework\boot\spring-boot\2.5.10\spring-boot-2.5.10.jar;C:\maven-repository\org\springframework\boot\spring-boot-autoconfigure\2.5.10\spring-boot-autoconfigure-2.5.10.jar;C:\maven-repository\org\springframework\boot\spring-boot-starter-logging\2.5.10\spring-boot-starter-logging-2.5.10.jar;C:\maven-repository\ch\qos\logback\logback-classic\1.2.10\logback-classic-1.2.10.jar;C:\maven-repository\ch\qos\logback\logback-core\1.2.10\logback-core-1.2.10.jar;C:\maven-repository\org\slf4j\slf4j-api\1.7.36\slf4j-api-1.7.36.jar;C:\maven-repository\org\apache\logging\log4j\log4j-to-slf4j\2.17.1\log4j-to-slf4j-2.17.1.jar;C:\maven-repository\org\apache\logging\log4j\log4j-api\2.17.1\log4j-api-2.17.1.jar;C:\maven-repository\org\slf4j\jul-to-slf4j\1.7.36\jul-to-slf4j-1.7.36.jar;C:\maven-repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\maven-repository\org\springframework\spring-core\5.3.16\spring-core-5.3.16.jar;C:\maven-repository\org\springframework\spring-jcl\5.3.16\spring-jcl-5.3.16.jar;C:\maven-repository\org\yaml\snakeyaml\1.28\snakeyaml-1.28.jar;C:\maven-repository\org\springframework\boot\spring-boot-starter-json\2.5.10\spring-boot-starter-json-2.5.10.jar;C:\maven-repository\com\fasterxml\jackson\core\jackson-databind\2.12.6\jackson-databind-2.12.6.jar;C:\maven-repository\com\fasterxml\jackson\core\jackson-annotations\2.12.6\jackson-annotations-2.12.6.jar;C:\maven-repository\com\fasterxml\jackson\core\jackson-core\2.12.6\jackson-core-2.12.6.jar;C:\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.12.6\jackson-datatype-jdk8-2.12.6.jar;C:\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.12.6\jackson-datatype-jsr310-2.12.6.jar;C:\maven-repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.12.6\jackson-module-parameter-names-2.12.6.jar;C:\maven-repository\org\springframework\boot\spring-boot-starter-tomcat\2.5.10\spring-boot-starter-tomcat-2.5.10.jar;C:\maven-repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.58\tomcat-embed-core-9.0.58.jar;C:\maven-repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.58\tomcat-embed-el-9.0.58.jar;C:\maven-repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.58\tomcat-embed-websocket-9.0.58.jar;C:\maven-repository\org\springframework\spring-web\5.3.16\spring-web-5.3.16.jar;C:\maven-repository\org\springframework\spring-beans\5.3.16\spring-beans-5.3.16.jar;C:\maven-repository\org\springframework\spring-webmvc\5.3.16\spring-webmvc-5.3.16.jar;C:\maven-repository\org\springframework\spring-aop\5.3.16\spring-aop-5.3.16.jar;C:\maven-repository\org\springframework\spring-context\5.3.16\spring-context-5.3.16.jar;C:\maven-repository\org\springframework\spring-expression\5.3.16\spring-expression-5.3.16.jar;C:\maven-repository\org\projectlombok\lombok\1.18.22\lombok-1.18.22.jar" com.dyit.Main

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.5.10)

2022-03-12 10:28:33.547  INFO 17592 --- [           main] com.dyit.Main                            : Starting Main using Java 1.8.0_311 on XTZJ-20220114OE with PID 17592 (D:\idea-workspace\springboot-hello\target\classes started by Administrator in D:\idea-workspace\springboot-hello)
2022-03-12 10:28:33.552  INFO 17592 --- [           main] com.dyit.Main                            : No active profile set, falling back to 1 default profile: "default"
2022-03-12 10:28:35.513  INFO 17592 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8099 (http)
2022-03-12 10:28:35.529  INFO 17592 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2022-03-12 10:28:35.530  INFO 17592 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.58]
2022-03-12 10:28:35.677  INFO 17592 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2022-03-12 10:28:35.677  INFO 17592 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2015 ms
2022-03-12 10:28:36.264  INFO 17592 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8099 (http) with context path ''
2022-03-12 10:28:36.278  INFO 17592 --- [           main] com.dyit.Main                            : Started Main in 3.802 seconds (JVM running for 8.058)
2022-03-12 10:29:01.024  INFO 17592 --- [nio-8099-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-03-12 10:29:01.025  INFO 17592 --- [nio-8099-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2022-03-12 10:29:01.028  INFO 17592 --- [nio-8099-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms

springboot的开发流程

maven

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BqM9z7Dd-1647088911754)(D:\dyit\20220312\笔记\images\image-20220312112626359.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fF7WWbhT-1647088911755)(D:\dyit\20220312\笔记\images\image-20220312112728155.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OSkrqtFU-1647088911755)(D:\dyit\20220312\笔记\images\image-20220312112835827.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qRQmOSlA-1647088911756)(D:\dyit\20220312\笔记\images\image-20220312112925354.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ol8x7mw0-1647088911757)(D:\dyit\20220312\笔记\images\image-20220312113015890.png)]

引用依赖

起步依赖 <parent>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.10</version>
    </parent>

项目依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${project.lombok.version}</version>
        </dependency>
    </dependencies>

启动类

启动springboot项目

@SpringBootApplication
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class);
    }
}

配置文件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rq5v2Yr7-1647088911758)(D:\dyit\20220312\笔记\images\image-20220312115452343.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fMfLg1II-1647088911758)(D:\dyit\20220312\笔记\images\image-20220312115827455.png)]

#总调度配置, 激活application-dev.yml文件
spring:
  profiles:
    active: dev
#开发环境

server:
  port: 8099

业务代码

dto

@Data
@NoArgsConstructor
@AllArgsConstructor
public class HttpResp {

    private int code;
    private String msg;
    private Object result;
    private Date time;
}

controller

package com.dyit.springboot.controller;

import com.dyit.springboot.dto.HttpResp;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/first")
public class HelloControlller {

    @GetMapping("/hello")
    public HttpResp hello(){
        return new HttpResp(1000,"springboot-deatails",null,new Date());
    }
}

restful测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lE1sF2lb-1647088911759)(D:\dyit\20220312\笔记\images\image-20220312141242270.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yEbrFUlr-1647088911760)(D:\dyit\20220312\笔记\images\image-20220312141258574.png)]

部署

打包

? |包

? |—jar (java)

? |—war (javaee)

引入maven打包的插件

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

idea的右侧位置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FIT7GmTl-1647088911760)(D:\dyit\20220312\笔记\images\image-20220312141851077.png)] [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4p3UroTL-1647088911761)(D:\dyit\20220312\笔记\images\image-20220312142044112.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oGsADnId-1647088911762)(D:\dyit\20220312\笔记\images\image-20220312142157291.png)]

部署

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FOSn0DoK-1647088911762)(D:\dyit\20220312\笔记\images\image-20220312142343619.png)]

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-13 21:36:26  更:2022-03-13 21:37:46 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 8:28:54-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码