【Spring教程26】Spring框架实战:从零开始学习SpringMVC 之 bean加载控制

news2024/10/7 20:36:27

目录

  • 1 问题分析
  • 2 思路分析
  • 3 环境准备
  • 4 设置bean加载控制
  • 5 知识点1:@ComponentScan

欢迎大家回到《Java教程之Spring30天快速入门》,本教程所有示例均基于Maven实现,如果您对Maven还很陌生,请移步本人的博文《如何在windows11下安装Maven并配置以及 IDEA配置Maven环境》,本文的上一篇为《SpringMVC入门案例总结与SpringMVC工作流程分析》
在这里插入图片描述

1 问题分析

入门案例的内容已经做完了,在入门案例中我们创建过一个SpringMvcConfig的配置类,再回想前面咱们学习Spring的时候也创建过一个配置类SpringConfig。这两个配置类都需要加载资源,那么它们分别都需要加载哪些内容?
我们先来看下目前我们的项目目录结构:
在这里插入图片描述

  • config目录存入的是配置类,写过的配置类有:
    • ServletContainersInitConfig
    • SpringConfig
    • SpringMvcConfig
    • JdbcConfig
    • MybatisConfig
  • controller目录存放的是SpringMVC的controller类
  • service目录存放的是service接口和实现类
  • dao目录存放的是dao/Mapper接口

controller、service和dao这些类都需要被容器管理成bean对象,那么到底是该让SpringMVC加
载还是让Spring加载呢?

  • SpringMVC加载其相关bean(表现层bean),也就是controller包下的类
  • Spring控制的bean
    • 业务bean(Service)
    • 功能bean(DataSource,SqlSessionFactoryBean,MapperScannerConfigurer等)

分析清楚谁该管哪些bean以后,接下来要解决的问题是如何让Spring和SpringMVC分开加载各自的内容。

在SpringMVC的配置类SpringMvcConfig中使用注解@ComponentScan,我们只需要将其扫描范围设置到controller即可,如
在这里插入图片描述
在Spring的配置类SpringConfig中使用注解@ComponentScan ,当时扫描的范围中其实是已经包含
了controller,如:
在这里插入图片描述
从包结构来看的话,Spring已经多把SpringMVC的controller类也给扫描到,所以针对这个问题
该如何解决,就是咱们接下来要学习的内容。
概况的描述下咱们现在的问题就是因为功能不同,如何避免Spring错误加载到SpringMVC的bean?

2 思路分析

针对上面的问题,解决方案也比较简单,就是:

  • 加载Spring控制的bean的时候排除掉SpringMVC控制的备案

具体该如何排除,有两种方式来解决:

  • 方式一:Spring加载的bean设定扫描范围为com.itheima,排除掉controller包中的bean
  • 方式二:Spring加载的bean设定扫描范围为精准范围,例如service包、dao包等
  • 方式三:不区分Spring与SpringMVC的环境,加载到同一个环境中[了解即可]

3 环境准备

  • 创建一个Web的Maven项目
  • pom.xml添加Spring依赖
<?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.itheima</groupId>
<artifactId>springmvc_02_bean_load</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
16 <version>3.1.0</version>
17 <scope>provided</scope>
18 </dependency>
19 <dependency>
20 <groupId>org.springframework</groupId>
21 <artifactId>spring-webmvc</artifactId>
22 <version>5.2.10.RELEASE</version>
23 </dependency>
24 <dependency>
25 <groupId>com.alibaba</groupId>
26 <artifactId>druid</artifactId>
27 <version>1.1.16</version>
28 </dependency>
29
30 <dependency>
31 <groupId>org.mybatis</groupId>
32 <artifactId>mybatis</artifactId>
33 <version>3.5.6</version>
34 </dependency>
35
36 <dependency>
37 <groupId>mysql</groupId>
38 <artifactId>mysql-connector-java</artifactId>
39 <version>5.1.47</version>
40 </dependency>
41
42 <dependency>
43 <groupId>org.springframework</groupId>
44 <artifactId>spring-jdbc</artifactId>
45 <version>5.2.10.RELEASE</version>
46 </dependency>
47
48 <dependency>
49 <groupId>org.mybatis</groupId>
50 <artifactId>mybatis-spring</artifactId>
51 <version>1.3.0</version>
52 </dependency>
53 </dependencies>
54
55 <build>
56 <plugins>
57 <plugin>
58 <groupId>org.apache.tomcat.maven</groupId>
59 <artifactId>tomcat7-maven-plugin</artifactId>
60 <version>2.1</version>
61 <configuration>
<port>80</port>
63 <path>/</path>
64 </configuration>
65 </plugin>
66 </plugins>
67 </build>
68 </project>
  • 创建对应的配置类
public class ServletContainersInitConfig extends
AbstractDispatcherServletInitializer {
2 protected WebApplicationContext createServletApplicationContext() {
3 AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
4 ctx.register(SpringMvcConfig.class);
5 return ctx;
6 }
7 protected String[] getServletMappings() {
8 return new String[]{"/"};
9 }
10 protected WebApplicationContext createRootApplicationContext() {
11 return null;
12 }
13 }
14
15 @Configuration
16 @ComponentScan("com.itheima.controller")
17 public class SpringMvcConfig {
18 }
19
20 @Configuration
21 @ComponentScan("com.itheima")
22 public class SpringConfig {
23 }
  • 编写Controller,Service,Dao,Domain类
@Controller
2 public class UserController {
3
4 @RequestMapping("/save")
5 @ResponseBody
6 public String save(){
7 System.out.println("user save ...");
8 return "{'info':'springmvc'}";
}
}
public interface UserService {
public void save(User user);
}
@Service
public class UserServiceImpl implements UserService {
public void save(User user) {
System.out.println("user service ...");
}
}
public interface UserDao {
@Insert("insert into tbl_user(name,age)values(#{name},#{age})")
public void save(User user);
}
public class User {
private Integer id;
private String name;
private Integer age;
//setter..getter..toString略
}

在这里插入图片描述

4 设置bean加载控制

方式一:修改Spring配置类,设定扫描范围为精准范围。

@Configuration
@ComponentScan({"com.itheima.service","comitheima.dao"})
public class SpringConfig {
}

说明:
上述只是通过例子说明可以精确指定让Spring扫描对应的包结构,真正在做开发的时候,因为Dao最终是交给MapperScannerConfigurer对象来进行扫描处理的,我们只需要将其扫描到service包即可。

方式二:修改Spring配置类,设定扫描范围为com.itheima,排除掉controller包中的bean

@Configuration
@ComponentScan(value="com.itheima",
	excludeFilters=@ComponentScan.Filter(
		type = FilterType.ANNOTATION,
		classes = Controller.class
	)
)
public class SpringConfig {
}
  • excludeFilters属性:设置扫描加载bean时,排除的过滤规则
  • type属性:设置排除规则,当前使用按照bean定义时的注解类型进行排除
    • ANNOTATION:按照注解排除
    • ASSIGNABLE_TYPE:按照指定的类型过滤
    • ASPECTJ:按照Aspectj表达式排除,基本上不会用
    • REGEX:按照正则表达式排除
    • CUSTOM:按照自定义规则排除

大家只需要知道第一种ANNOTATION即可

  • classes属性:设置排除的具体注解类,当前设置排除@Controller定义的bean

如何测试controller类已经被排除掉了

public class App{
public static void main (String[] args){
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
		System.out.println(ctx.getBean(UserController.class));
	}
}

如果被排除了,该方法执行就会报bean未被定义的错误
在这里插入图片描述
出现问题的原因是,

  • Spring配置类扫描的包是com.itheima
  • SpringMVC的配置类,SpringMvcConfig上有一个@Configuration注解,也会被Spring扫描到
  • SpringMvcConfig上又有一个@ComponentScan,把controller类又给扫描进来了
  • 所以如果不把@ComponentScan注释掉,Spring配置类将Controller排除,但是因为扫描到SpringMVC的配置类,又将其加载回来,演示的效果就出不来
  • 解决方案,也简单,把SpringMVC的配置类移出Spring配置类的扫描范围即可。

最后一个问题,有了Spring的配置类,要想在tomcat服务器启动将其加载,我们需要修改ServletContainersInitConfig

1 public class ServletContainersInitConfig extends
AbstractDispatcherServletInitializer {
2 protected WebApplicationContext createServletApplicationContext() {
3 AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
4 ctx.register(SpringMvcConfig.class);
5 return ctx;
6 }
7 protected String[] getServletMappings() {
8 return new String[]{"/"};
9 }
10 protected WebApplicationContext createRootApplicationContext() {
11 AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
12 ctx.register(SpringConfig.class);
13 return ctx;
14 }
15 }

对于上述的配置方式,Spring还提供了一种更简单的配置方式,可以不用再去创建AnnotationConfigWebApplicationContext对象,不用手动register对应的配置类,如何实现?

public class ServletContainersInitConfig extends
AbstractAnnotationConfigDispatcherServletInitializer {

protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}

5 知识点1:@ComponentScan

名称@ComponentScan
类型类注解
位置类定义上方
作用设置spring配置类扫描路径,用于加载使用注解格式定义的bean
相关属性excludeFilters:排除扫描路径中加载的bean,需要指定类别(type)和具体项(classes)includeFilters:加载指定的bean,需要指定类别(type)和具体项(classes)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1305657.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

智能优化算法应用:基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于哈里斯鹰算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.哈里斯鹰算法4.实验参数设定5.算法结果6.…

【尘缘送书第七期】2023年度盘点:智能汽车 | 自动驾驶 | 车联网

【文末送书】今天推荐几本智能汽车 | 自动驾驶 | 车联网领域优质书籍。 目录 引言1 《智能汽车》2 《SoC底层软件低功耗系统设计与实现》3 《SoC设计指南》4 《蜂窝车联网与网联自动驾驶》5 《智能汽车网络安全权威指南&#xff08;上册&#xff09;》6 《智能汽车网络安全权威…

Keil 编译输出信息分析:Program size: Code, RO-data , RW-data, ZI-data

一般 MCU 包含的存储空间有&#xff1a;片内 Flash 与片内 RAM&#xff0c;RAM 相当于内存&#xff0c;Flash 相当于硬盘。编译器会将一个程序分类为好几个部分&#xff0c;分别存储在 MCU 不同的存储区。 如图所示&#xff0c;在Keil中编译工程成功后&#xff0c;在下面的Bul…

智能优化算法应用:基于闪电搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于闪电搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于闪电搜索算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.闪电搜索算法4.实验参数设定5.算法结果6.…

NCNN 源码学习【二】:模型加载

​ 正文 这次先来看一段NCNN应用代码中&#xff0c;最先出现的部分&#xff0c;模型加载 ncnn::Net squeezenet; squeezenet.load_param("squeezenet_v1.1.param"); squeezenet.load_model("squeezenet_v1.1.bin");首先我们可以看到一个 ncnn的类Net&am…

【@Cacheable的使用,及设置过期时间 配置方式】

Cacheable的使用&#xff0c;及设置过期时间 配置方式 使用方式 使用方式 Cacheable(cacheNames “ssss#30” ,key “#aaa‘‘#beginTime’’#endTime”) cacheNames/value &#xff1a;用来指定缓存组件的名字key &#xff1a;缓存数据时使用的 key&#xff0c;可以用它来指…

【Oracle】backup备份时报错ORA-19809,ORA-9804

Oracle备份数据库时报错 ORA-19809: limit exceeded for recovery files ORA-19804: cannot reclaim 10305536 bytes disk space from 4385144832 limit 1.清理过时的备份&#xff1a; 使用RMAN删除不再需要的过时备份&#xff0c;以释放空间。执行以下命令&#xff1a; DEL…

模块一——双指针:11.盛最多水的容器

文章目录 题目解析算法原理解法一&#xff1a;暴力枚举(超时&#xff09;解法二&#xff1a;双指针单调性 代码实现暴力枚举(超时&#xff09;双指针单调性(时间复杂度为O(N)&#xff0c;空间复杂度为O(1)&#xff09; 题目解析 题目链接&#xff1a;11.盛最多水的容器 这道题…

uniapp实战 —— 轮播图【数字下标】(含组件封装,点击图片放大全屏预览)

组件封装 src\components\SUI_Swiper2.vue <script setup lang"ts"> import { ref } from vue const props defineProps({config: Object, })const activeIndex ref(0) const change: UniHelper.SwiperOnChange (e) > {activeIndex.value e.detail.cur…

C# Socket通信从入门到精通(14)——多个异步UDP客户端C#代码实现

前言: 在之前的文章C# Socket通信从入门到精通(13)——单个异步UDP客户端C#代码实现我介绍了单个异步Udp客户端的c#代码实现,但是有的时候,我们需要连接多个服务器,并且对于每个服务器,我们都有一些比如异步发送、异步接收的操作,那么这时候我们使用之前单个异步Udp客…

jmeter接口测试之登录测试

注册登录_登陆接口文档 1.登录 请求地址&#xff1a; POST xxxxxx/Home/Login 请求参数&#xff1a; args{LoginName:"mtest", // 登录名&#xff0c;可以为用户名或邮箱Password:"123456" // 密码" }响应数据&#xff1a; 成功 {"S…

浅谈linux缓冲区的认识!

今天来为大家分享一波关于缓冲区的知识&#xff01;那么既然我们要谈缓冲区&#xff0c;那么就得从是什么&#xff1f;为什么&#xff1f;有什么作用这几个方面来谈论一下缓冲区&#xff01;然后再通过一些代码来更加深刻的理解缓冲区的知识&#xff01; 引言&#xff1a; 是…

ServletJSP

Servlet 1.Servlet生命周期 2.HttpServletRequest与HttpServletResponse 2.1HttpServletRequest 获取请求参数 请求乱码问题&#xff1a; 请求转发 request作用域 2.2HttpServletResponse 输出 乱码 重定向 3.Cookie 4.Sessions 5.ServletContext 获取方式及常用方法&a…

selenium自动化(中)

显式等待与隐式等待 简介 在实际工作中等待机制可以保证代码的稳定性&#xff0c;保证代码不会受网速、电脑性能等条件的约束。 等待就是当运行代码时&#xff0c;如果页面的渲染速度跟不上代码的运行速度&#xff0c;就需要人为的去限制代码执行的速度。 在做 Web 自动化时…

经典策略筛选-20231212

策略1&#xff1a; 龙头战法只做最强&#xff1a;国企改革 ----四川金顶 1、十日交易内出现 涨停或 &#xff08;涨幅大于7个点且量比大于3&#xff09; 2、JDK MACD RSI OBV BBI LWR MTM 六指标共振 3、均线多头 4、 筹码峰 &#xff08;锁仓&#xff09; 5、现价>…

虹科分享 | CanEasy多场景应用,让汽车总线测试更简单

CanEasy是一个基于Windows的总线工具&#xff0c;用于分析和测试CAN、CAN FD和LIN以及汽车以太网系统。通过高度自动化和简单的配置模拟总线流量&#xff0c;CanEasy可用于分析真实网络、模拟虚拟系统&#xff0c;以及在整个开发过程中进行剩余总线模拟&#xff0c;实现从测试到…

FFmpeg-基础组件-AVFrame

本章主要介绍FFmpeg基础组件AVFrame. 文章目录 1.结构体成员2.成员函数AVFrame Host内存的获取 av_frame_get_bufferAVFrame device内存获取av_hwframe_get_buffer&#xff08;&#xff09; 1.结构体成员 我们把所有的代码先粘贴上来&#xff0c;在后边一个一个解释。 typede…

鸿蒙Stage模型开发—创建你的第一个ArkTS应用

Stage模型开发概述 基本概念 下图展示了Stage模型中的基本概念。 图1 Stage模型概念图 UIAbility组件和ExtensionAbility组件 Stage模型提供UIAbility和ExtensionAbility两种类型的组件&#xff0c;这两种组件都有具体的类承载&#xff0c;支持面向对象的开发方式。UIAbility…

ARM:作业3

按键中断代码编写 代码: key_it.h #ifndef __KEY_IT_H__ #define __KEY_IT_H__#include "stm32mp1xx_gpio.h" #include "stm32mp1xx_exti.h" #include "stm32mp1xx_rcc.h" #include "stm32mp1xx_gic.h"void key1_it_config(); voi…

冯诺依曼体系与操作系统的理解

目录 一.冯诺依曼体系结构 存储分级 为什么程序运行之前&#xff0c;必须加载到内存上&#xff1f; 二.操作系统 操作系统是什么&#xff1f; 为什么需要操作系统&#xff1f; 操作系统是如何管理软硬件资源&#xff1f; 一.冯诺依曼体系结构 我们常见的计算机&#xff…