Spring – Wasting_Misaka.Blog https://forelink.top Hso! Fri, 13 Sep 2024 15:47:38 +0000 zh-Hans hourly 1 https://wordpress.org/?v=6.7.1 春靴+兔 TopicMode https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-topicmode/ https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-topicmode/#respond Fri, 13 Sep 2024 15:47:35 +0000 https://forelink.top/?p=570 简介
image.png

使用SpringBoot + RabbitMQ 实现需求: 通过 在HTML页面中填写表单并提交 发起 HTTP 请求来调用生产者方法发送消息 格式如 test.orange.test 并将Message输出打印到控制台上。

Topic 程序

配置类

在 spring框架的amcq中,提供了 队列,交换机和绑定关系的构建方法(Builder) 在使用 SpringBoot 提供 RabbitMQ 服务时,活用构建器可以简化开发流程。

Spring框架的amqp.core包提供了如下构建器: QueueBuilder ExchangeBuilder BindindBuilder 以点分隔接收参数,队列与交换机以 build() 结尾 绑定关系Binding以 noargs() 或者 and() 结尾

在构建过程中可以查看后续方法的类型。 image.png

import org.springframework.amqp.core.*;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
  
/**  
 * */  
@Configuration  
public class TopicConfig {  
    // 1.交换机 标识使用@Qualify注解调用这个bean  
    @Bean("topicExchange")  
    public Exchange topicExchange(){  
        // 创建一个 topic类型 的交换机  
        return ExchangeBuilder.topicExchange("topicExchange").durable(false).build();  
    }  
    // 2.队列  
    @Bean("topicQueue1")  
    public Queue topicQueue1(){  
        return QueueBuilder.durable("topicQueue1").build();  
    }  
    @Bean("topicQueue2")  
    public Queue topicQueue2(){  
        return QueueBuilder.durable("topicQueue2").build();  
    }  
    // 3.绑定Topic关系  
    @Bean  
    public Binding Binding1(@Qualifier("topicQueue1") Queue queue,@Qualifier("topicExchange") Exchange exchange){  
        return BindingBuilder.bind(queue).to(exchange).with("*.orange.*").noargs();  
    }  
  
    @Bean  
    public Binding binding2(@Qualifier("topicQueue2") Queue queue,@Qualifier("topicExchange") Exchange exchange){  
        return BindingBuilder.bind(queue).to(exchange).with("*.*.rabbit").noargs();  
    }  
  
    @Bean  
    public Binding binding3(@Qualifier("topicQueue2") Queue queue,@Qualifier("topicExchange") Exchange exchange){  
        return BindingBuilder.bind(queue).to(exchange).with("lazy.#").noargs();  
    }  
  
}

HTML 页面

准备一个 HTML 页面,包含routingKey Message 的表单。

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Topic Test</title>  
</head>  
<body>  
    <form action="http://localhost:8080/topic" method="get" >  
        routing key: <input type="text" name="routingKey">  
        message : <input type="text" name="message"></input>  
        <input type="submit" value="提交">  
    </form></body>  
</html>
<!--
    form 表单
        action发送表单中的数据到action的url里,
               url为空时发送到当前页面
        method
            get 有url长度限制
            post发送到f12中网络请求中,无网络限制
    input
        type
            text 文本类型,可操作
            submit 按钮类型,可点击
        name
            是必须的属性
        value
            框框中的值
-->

在浏览器中打开的效果如下

image.png

生产者

新建生产者类 ropicProducer 先创建一个Spring框架中的 RabbitTemplate 实现类 该类已装载在 Bean 容器中,设置AutoWired自动获取该对象

然后提供一个 sendMessage 方法,包含 routingKeymessage 形参,方便外部传参调用。

import org.springframework.amqp.rabbit.core.RabbitTemplate;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Component;  
  
@Component  
public class TopicProducer {  
    // 创建一个rabbitTemplate对象  
    private RabbitTemplate rabbitTemplate;  
    private String exchangeName = "topicExchange";  
  
    @Autowired  
    public TopicProducer(RabbitTemplate rabbitTemplate) {  
        this.rabbitTemplate = rabbitTemplate;  
    }  
    // sendMessage 方法  
    public void sendMessage(String routingKey,String message) {  
        rabbitTemplate.convertAndSend(exchangeName, routingKey, message);  
    }  
}

控制器

新建控制器 TopicController 用于响应HTTP请求,并执行生产者发送消息的 sendMessage 方法 创建一个生产者对象 topicProducer 用以调用发送消息的方法

并提供一个 GetMapping 方法, 在接收到HTTP页面发来的请求后, 将表单中包含的 routingKeyMessage 传给 sendMessage() 方法

import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class TopicController {  
  
    private final TopicProducer topicProducer;  
  
    public TopicController(TopicProducer topicProducer) {  
        this.topicProducer = topicProducer;  
    }  

    @GetMapping("/topic")  
    public String sendMessage(String routingKey,String message){  
        topicProducer.sendMessage(routingKey,message);  
        return "routingKey: "+routingKey+"\nmessage: "+message;  
    }  
}

测试效果

将主程序运行起来, 打开 html 页面, 通过表单提交三条测试信息和一条无关信息.

image.png

在控制台中可以大致确认信息达到了队列

image.png

消费者

新建两个消费者类, 分别用以处理两个队列的消息 并通过@RabbitListener 注解监听队列, 当取到队列的信息时, 会将参数传入注解下的方法并自动调用

import org.springframework.amqp.rabbit.annotation.RabbitListener;  
import org.springframework.stereotype.Component;  
  
@Component  
public class TopicConsumer1 {  
    private final String queueName = "topicQueue1";  
    @RabbitListener(queues = queueName)  
    public void recv(String message) {  
        System.out.println("C1 receive message : " + message);  
    }  
}

消费者2中的 QueueName 改为 topicQueue2 控制台输出信息中的 C1 改为 C2 加以区分

运行

运行代码,拿到并处理了队列中积压的信息 image.png

打开 html 页面再测试几组数据,返回了正确的结果 image.png

]]>
https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-topicmode/feed/ 0
春靴+兔 入门程序 https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-%e5%85%a5%e9%97%a8%e7%a8%8b%e5%ba%8f/ https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-%e5%85%a5%e9%97%a8%e7%a8%8b%e5%ba%8f/#respond Fri, 13 Sep 2024 15:46:27 +0000 https://forelink.top/?p=568 简介:

将RabbitMQ 整合到 SpringBoot中。 并实现一个入门程序。

入门程序

导入依赖

在IDEA 创建SpringBoot工程前勾选以下依赖 image.png

修改配置文件

修改 application.properties 或 applications.yml 文件, 加入RabbitMQ 的配置信息

image.png

1. 生产者(发送消息)

创建一个 MessageProducer 类,用于发送消息

package com.wastingmisaka.springbootrabbitmq;  
  
import org.springframework.amqp.rabbit.core.RabbitTemplate;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean;  
import org.springframework.stereotype.Component;  
  
/**  
 * 生产者类  
 */  
@Component  
public class MessageProducer {  
    private final RabbitTemplate rabbitTemplate;  
  
    @Autowired  
    public MessageProducer(RabbitTemplate rabbitTemplate) {  
        this.rabbitTemplate = rabbitTemplate;  
    }  
  
    public void sendMessage(String message) {  
        System.out.println("Sending message: " + message);  
        rabbitTemplate.convertAndSend("helloQueue", message);  
    }  
}

2. 配置队列

创建一个 RabbitMQConfig 类,用于配置队列、交换器和绑定等。

package com.wastingmisaka.springbootrabbitmq;  

import org.springframework.amqp.core.Queue;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
  
/**  
 * 配置类  
 * @Congiuration 告知Spring这是一个配置类
 */  
@Configuration  
public class RabbitMQConfig {  
    @Bean  
    public Queue helloQueue() {  
        return new Queue("helloQueue", false);  
        // 创建一个 helloQueue 的队列,且不需要持久化。
    }  
}

此处仅配置了队列。

3. 消费者(接收消息)

package com.wastingmisaka.springbootrabbitmq;  
  
import org.springframework.amqp.rabbit.annotation.RabbitListener;  
import org.springframework.stereotype.Component;  
  
/**  
 * 消费者类  
 */  
  
@Component  
public class MessageConsumer {  
    @RabbitListener(queues = "helloQueue")  
    public void receiveMessage(String message) {  
        System.out.println("Received message: " + message);  
    }  
}

@RabbitListener 注解用来监听指定队列的消息,当有消息到达时,携带信息参数自动触发方法执行。

4. 控制器(发起请求)

创建一个用于发起HTTP请求的控制器

package com.wastingmisaka.springbootrabbitmq;  
  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RequestParam;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class MessageController {  
  
    private final MessageProducer messageProducer;  
  
    public MessageController(MessageProducer messageProducer) {  
        this.messageProducer = messageProducer;  
    }  
  
    @GetMapping("/test")  
    public String test(){  
        String msg = "hello,world";  
        messageProducer.sendMessage(msg);  
        return "Message sent: "+msg;  
    }  
  
  
    @GetMapping("/send")  
    public String sendMessage(@RequestParam String message) {  
        messageProducer.sendMessage(message);  
        return "Message sent: "+message;  
    }  
}

其中 /test 请求路径包含了一个测试方法,向RabbitMQ发送 hello,world 消息。 /send 请求路径可以添加参数。

测试结果:

image.png

控制台对应的方法被调用。 且RabbitMQ管理台中存在helloQueue 队列

image.png

页面也返回了正确的信息

image.png

]]>
https://forelink.top/index.php/2024/09/13/%e6%98%a5%e9%9d%b4%e5%85%94-%e5%85%a5%e9%97%a8%e7%a8%8b%e5%ba%8f/feed/ 0
SpringMVC-响应 https://forelink.top/index.php/2024/07/31/springmvc-%e5%93%8d%e5%ba%94/ Wed, 31 Jul 2024 09:06:31 +0000 https://forelink.top/?p=405 SpringMVC-响应

响应页面:

用这种格式跳转页面

// 响应页面/跳转页面
@RequestMapping("/r1")
public String toJumpPage(){
    System.out.println("跳转页面");
    return "hso.jsp";
}

响应文本数据:

加入@ResponseBody注解返回文本数据

// 响应文本数据
@RequestMapping("/r2")
@ResponseBody
public String toText(){
    System.out.println("响应文本数据");
    // 如果直接返回字符串,会被认为是一个页面
    // 需要加上ResponseBody注解
    return "response text";
}

响应实体类对象:

加入 @ResponseBody 注解返回 json 格式数据

// 响应实体类对象
@RequestMapping("/r3")
public User toJsonUser(){
    System.out.println("响应实体类json数据");
    User user = new User();
    user.setName("forelink");
    user.setId(8);
    return user;
}

​ 靠 jackson 依赖完成

@ResponseBody注解:

方法注解,加载 SpringMVC 控制器方法定义上方 能设置当前控制器返回值作为 响应体

使用了类型转换器 HttpMessageConverter 接口

]]>
SpringMVC-json&日期参数传递 https://forelink.top/index.php/2024/07/31/springmvc-json%e6%97%a5%e6%9c%9f%e5%8f%82%e6%95%b0%e4%bc%a0%e9%80%92/ Wed, 31 Jul 2024 09:05:38 +0000 https://forelink.top/?p=403 json参数传递

SpringMVC不能转化json

导入依赖:

//pom.xml
<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
</dependency>

开启功能:

在SpringMVC配置类定义上方加入 @EnableWebMvc 注解

@EnableWebMvc 是配置类注解,能开启SpringMVC的多项辅助功能

//SpringMvcConfig.java
@Configuration
@ComponentScan("com.forelink.controller")
//开启SpringMVC的多项辅助功能
@EnableWebMvc
public class SpringMvcConfig {
}

json 转 List:

在方法形参名加@RequestBody,就可以读取请求体中的json数据,并转换为List格式的数据。

@RequestBody 是形参注解,加载SpringMVC控制器方法形参定义的前面

//接受请求体中的json数据
@RequestMapping("/cp5")
    @ResponseBody
    public String cp5(@RequestBody List<String> name){
        System.out.println(name);
        return "{'module':'user cp5'}";
    }

此注解一个处理器方法只能使用一次。

json转实体类:

和list同理,json中的变量名匹配到类中的成员变量时会为类成员变量赋值。

RequestBody和RequestParam:

@RequestParam 用于接收url地址传参,表单传参 @RequestBody用于接受json数据

后期开发中,发送json格式数据为主,@RequestBody应用较广 如果发送非json格式数据,选用@RequestParam接受请求参数

日期类型数据:

概述:

日期类型数据基于系统不同格式而存在差异,如:

​ YYYY/MM/DD ​ YYYY-MM-DD ​ MM/DD/YYYY

DateTimeFormat注解:

@DateTimeFormat 形参注解,加在SpringMVC控制器方法形参前面 能设定日期时间型数据格式

//接受url地址中的时间数据
//用DateTimeFormat注解指定接受的日期格式
@RequestMapping("/cp6")
@ResponseBody
public String cp6(Date date, 
                  @DateTimeFormat(pattern="yyyy-MM-dd") Date date1, 
                  @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date date2){
    System.out.println("date: " + date);
    System.out.println("date1: " + date1);
    System.out.println("date2: " + date2);
    return "{'module':'user cp6'}";
}

测试url:

http://localhost:8080/user/cp6?date=2024/07/05&date1=2025-07-05&date2=2024/05/07%203:45:32

原理:

用到了 类型转换器 ==> Convert接口 其中包含日期时间的转换。

包含

请求参数年龄 日期格式转换

@EnableWebMvc注解和类型转换器:

开启@EnableWebMvc功能注解后,能根据类型匹配对应的类型转换器

]]>
2.SpringMVC入门案例 https://forelink.top/index.php/2024/07/20/2-springmvc%e5%85%a5%e9%97%a8%e6%a1%88%e4%be%8b/ Sat, 20 Jul 2024 01:29:26 +0000 https://forelink.top/?p=350 SpringMVC入门案例

前期准备:

  1. 首先要导入SpringMVC坐标与Servlet坐标


  2. 创建SpringMVC控制器类(等同于Servlet功能)


    @Controller
    public class UserController{
    @RequestMapping("/save")
    @ResponseBody
    public String save(String name){
    sout("springmvc save name ==> " + name);
    return "{'module':'springmvc save'}";
    }
    }

    功能在控制器(Controller)中实现


  3. 初始化SpringMVC环境(同Spring环境),设定SpringMVC加载对应的Bean


    @Configuration
    @ComponentScan("com.forelink.controller")
    public class SpringMvcConfig{
    }

  4. 初始化Servlet容器,加载SpringMVC环境,并设置SpringMVC技术处理的请求


  5. 导入Tomcat插件


创建模块:

​ 选择New Module – Maven Archetype – 选择JDK – Archetype选择后缀为webapp的骨架

​ 在pom.xml中,可以把多余的 和 删除 ​ 右键main文件夹,新建一个源码目录java,然后mark directory为source code源码目录(其实能自动化)

​ 然后导入springmvc和servlet的坐标

​ springmvc导入org.springframework即可。

创建控制器:

在java下建立文件内容如下

package com.forelink.controller; //包名
import org.springframework.stereotype.Controller; //导入控制器包
import org.springframework.web.bind.annotation.RequestMapping;

//2.定义Controller
//2.1使用@Controller定义Bean
@Controller //类名前要加入注解
public class UserController {
    @RequestMapping("/save")
    public String save(){
        System.out.println("user save...");
        return "{'module':'springmvc'}";
    }
}

创建SpringMVC配置:

在forelink下创建一个config包用来存放配置文件,创建SpringMvcConfig

// 3. 创建springmvc的配置文件,加载controller对应的bean
package com.forelink.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.forelink.controller")
public class SpringMvcConfig {

}

创建Servlet:

启动服务器时,需要加载Spring,就需要做Tomcat容器启动的配置,来加载SpringMVC配置文件

//4. 定义一个servlet容器启动的配置类,在里面加载spring的配置
package com.forelink.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer{
    //重写三个方法
    //加载SpringMVC容器配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        //普通ctx不能用于web环境,要用web类型的ctx(下面的Web)
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //注册配置 会加载SpringMvcConfig的配置
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }
    //设置哪些请求归属SpringMVC管理
    @Override
    protected String[] getServletMappings() {
        //任何请求
        return new String[]{"/"};
    }
    //加载spring容器配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null; //只有MVC就不用管
    }
}

导入Tomcat插件:

在pom.xml中build项加入

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
    <finalName>springmvc_01_quickstart</finalName>
  </build>

启动程序(Maven启动):

点击运行按钮旁边的三个点,选择Edit,点击加号,然后选中Maven,修改项目地址,在 command line 中加入

tomcat7:run

然后点击确定,就可以看到这个程序通过maven方式启动。

报错总结:

报错内容:

​ 无法访问jakarta.servlet.ServletException

​ A child container failed during start

解决方法1:

​ 用SpringBoot,内嵌tomcat和maven。

解决方法2:

​ 把web.xml中没用的部分删掉,删到只剩下如下内容时,可以运行。

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
</web-app>
]]>
1.SpringMVC概述 https://forelink.top/index.php/2024/07/20/1-springmvc%e6%a6%82%e8%bf%b0/ Sat, 20 Jul 2024 01:28:59 +0000 https://forelink.top/?p=348 SpringMVC

内容:

请求与响应

REST风格

SSM整合

拦截器

学习目标:

  1. 掌握基于SpringMVC获取请求参数与响应json数据操作
  2. 熟练应用基于REST风格的请求路径设置与参数传递
  3. 能够根据实际业务建立前后端开发通信协议并进行实现
  4. 基于SSM整合技术开发任意业务模块功能

概述:

SpringMVC技术与Servlet技术功能等同,均属于web层开发技术

SpringMVC是一种基于Java实现MVC模型的轻量级Web框架 优点:使用简单,开发便捷 灵活性强

Servlet实现方法

@WebServlet("/user/save") //生效的路径
public class UserServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws Servlet Exception, IOException{
        //1.接受请求参数
        String name = req.getParameter("name");
        sout("servlet save name ==> " + name);
        //2.产生响应
        resp.setContentType("text/json;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        pw.write("{'module':'servlet save'}");//把内容显示到浏览器上
    }
    
    @Override
    protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws Servlet Exception, IOException{
        this.doGet(req,resp);
    }
}

SpringMVC实现方法

@Controller
public class UserController{
    @RequestMapping("/save")
    @ResponseBody
    public String save(String name){
        sout("springmvc save name ==> " + name);
        return "{'module':'springmvc save'}";
    }
    
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String name){
        sout("springmvc delete name ==> " + name);
        return "{'module':'springmvc delete'}";
    }
}

​ 用SpringMVC书写,开发更简洁,接受参数更方便,都封装在RequestBody中统一接受。

数据层:JDBC ==> MyBatis

表现层:Servlet ==> SpringMVC (web框架)

]]>
SpringMVC-请求参数传递类型 https://forelink.top/index.php/2024/07/19/springmvc-%e8%af%b7%e6%b1%82%e5%8f%82%e6%95%b0%e4%bc%a0%e9%80%92%e7%b1%bb%e5%9e%8b/ Fri, 19 Jul 2024 14:36:09 +0000 https://forelink.top/?p=346 请求参数传递类型

1. 请求参 !=形参

在方法形参中加入@RequestParam注解

void test(@RequestParam("name") String username)

2.接受实体类参数

创建一个User类,并导入到控制器中 这个类包含

变量:
    String name
    int id
Getter&Setter方法
ToString方法

请求中包含方法中需要的形参名时,即可获取到信息

3.接受array类型数据

如果只是接受 设要接受一个String的Array数组进入方法

public String cp3(String[] name)

每接受到一个等于形参名的请求名,就会将该数据存入数组中

4.接受List集合类型数据

要在方法参数名前加 @RequsetParam 注解

public String cp4(List<String> name)
]]>
SpringMVC-Get&Post请求接受参数 https://forelink.top/index.php/2024/07/19/springmvc-getpost%e8%af%b7%e6%b1%82%e6%8e%a5%e5%8f%97%e5%8f%82%e6%95%b0/ Fri, 19 Jul 2024 14:35:34 +0000 https://forelink.top/?p=343 Get&Post请求接受参数

url参数接受:

控制器写法:

@RequestMapping("/cp")
@ResponseBody
public String cp(String name,int id){
    System.out.println("name: " + name);
    System.out.println("id: " + id);
    return "{'module':'user cp'}";
}

请求方式:

//程序启动后在浏览器中访问
http://localhost:8080/user/cp?name=nihao&id=1

控制台输出结果:

name: nihao
id: 1

浏览器显示结果:

{'module':'user cp'}

表单参数接受:

表单格式:

form-data 可以携带文件

x-www-form-urlencoded 普通表单

表单中的参数名 对应 方法中的参数名 时,一样能接受到数据

控制台中文乱码问题解决:

在ServletContainerInitConfig加入Filter

//乱码处理 导入javax.servlet的包
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter1 = new CharacterEncodingFilter();
        filter1.setEncoding("UTF-8");
        return new Filter[]{filter1};
    }

*但是好像还是没有解决,应该是IDEA控制台问题。

]]>
SpringMVC请求路径映射 https://forelink.top/index.php/2024/07/19/springmvc%e8%af%b7%e6%b1%82%e8%b7%af%e5%be%84%e6%98%a0%e5%b0%84/ Fri, 19 Jul 2024 14:34:35 +0000 https://forelink.top/?p=340 请求路径

实现方法:

​ 在Controller上加入@RequestMapping注解实现

​ 具体使用方法:

@Controller
@RequestMapping("/book")
public class BookController {
    @RequestMapping("/save")
    @ResponseBody
    public String save(){
        System.out.println("Book save ...");
        return "{'module':'book save'}";
    }
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(){
        System.out.println("Book delete ...");
        return "{'module':'book delete'}";
    }
}

用浏览器1localhost:8080/book/delete 可以正常调用该方法

]]>
SpringMVC-Bean加载控制 https://forelink.top/index.php/2024/07/19/2-bean%e5%8a%a0%e8%bd%bd%e6%8e%a7%e5%88%b6/ Fri, 19 Jul 2024 14:33:35 +0000 https://forelink.top/?p=338 Bean加载控制

控制Bean加载:

在入门案例中,如果有不想被加载的bean,在Spring加载的bean加载Spring的时候有两种方式可以使用

方式:

​ Spring加载的bean设定扫描范围为com.forelink,排除掉controller包内的bean ​

//在ComponentScan注解后加入参数,限定扫描范围
@ComponentScan({"com.forelink.service","com.forelink.dao"})
public class SpringConfig{
}

​ 扫描Dao包,通用性会好 ​ 如果不用Mybatis技术,用其他技术,也要扫描Dao包。 ​ 能把数据层包括进来,属于标准开发的一种 ​ 后续更改数据层就不用修改。

也可以使用排除的方法。

//使用排除方法
@ComponentScan(value="com.forelink",
    excludeFilters = @ComponentScan.Filter(
        //需要一个参数type,FilterType.[过滤策略]
        //此处是过滤注解
        type = FilterType.ANOTATION,
        //过滤 com.forelink 中的 Controller 注解
        classes = Controller.class
        
    )
)
public class SpringConfig{
}

​ 也有includeFilter,可以加载指定的bean。 ​ 可以写一个测试类进行效果测试

public class App {
    public static void main(String[] args) {
//        AnnotationConfigApplicationContext ctx = new     AnnotationConfigApplicationContext();
//        ctx.register(SpringConfig.class);
        //也可以用这种方式来注册Spring配置文件
        AnnotationConfigApplicationContext ctx = new         AnnotationConfigApplicationContext(SpringConfig.class);
     System.out.println(ctx.getBean(UserController.class));;
    }
}

​ 会弹出报错,提示加载不了带有Controller的Bean,成功。

​ 要注意带@configuration注解的,都有加载bean的功能。

​ Springboot中 通过Filter来对Bean的精细粒子度进行的控制

还有一种方式是,不对Spring会SpringMVC加以区分,都加载到环境中。 创建多个容器。

bean配置文件的加载:

​ ServletContainersInitConfig可以继承AbstractAnnotationConfigDispatcherServletInitializer,来简化开发流程

public class ServletContainerInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{
    //RootConfig配Spring的内容
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }
    //ServletConfig下配置SpringMVC的内容
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}
//与下列内容是一样的
//public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer{
//    @Override
//    protected WebApplicationContext createServletApplicationContext() {
//        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
//        ctx.register(SpringMvcConfig.class);
//        return ctx;
//    }
//    @Override
//    protected String[] getServletMappings() {
//        return new String[]{"/"};
//    }
//    @Override
//    protected WebApplicationContext createRootApplicationContext() {
//        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
//        ctx.register(SpringConfig.class);
//    }
//}
]]>