Spring中使用自带@Autowired注解实现策略模式

场景

SpringBoot中策略模式+工厂模式业务实例(接口传参-枚举类查询策略映射关系-执行不同策略)规避大量if-else:

SpringBoot中策略模式+工厂模式业务实例(接口传参-枚举类查询策略映射关系-执行不同策略)规避大量if-else_springboot编写策略工厂-CSDN博客

设计模式-策略模式在Java中的使用示例:

设计模式-策略模式在Java中的使用示例_java 多个状态用策略模式demo-CSDN博客

上面在讲策略模式具体在SpringBoot中应用时在规则工厂类中直接使用@Autowired注解将信号灯的规则全部注入。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;

/**
 * 信号灯规则工厂类
 */
@Component
public class SignalLightRulesFactory {

    //Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id 即前面@Component注解指定的名称,value值则为对应的策略实现类
    @Autowired
    Map<String,SignalLightRules> signalLightRulesStrategy;

    public  SignalLightRules getSignalLightRules(String signalLightKey){
        SignalLightRules signalLightRules = signalLightRulesStrategy.get(signalLightKey);
        return signalLightRules;
    }
}

这里的信号灯规则接口类

public interface SignalLightRules {

    List<SignalrightDevsDTO> getSignalrightDevsDtoList(String mineApiCode);

}

规则具体实现示例一

@Component(Constants.SIFANGJISIGNAL)
public class SiFangJiSignalLightRules implements SignalLightRules{


    @Override
    public List<SignalrightDevsDTO> getSignalrightDevsDtoList(String mineApiCode) {

        List<SignalrightDevsDTO> signalrightDevsDtoList = null;
        //省略
        return signalrightDevsDtoList;
    }
}

这里使用注解@Autowired将所有的声明类注入到map中。这是因为

Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id 即前面@Component注解指定的名称,

value值则为对应的策略实现类。

注:

博客:
霸道流氓气质-CSDN博客

实现

其实不光是map可以,如果是数组集合也可以,这块可以查看@Autowired注解的源码声明

​
/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.beans.factory.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a constructor, field, setter method, or config method as to be autowired by
 * Spring's dependency injection facilities. This is an alternative to the JSR-330
 * {@link javax.inject.Inject} annotation, adding required-vs-optional semantics.
 *
 * <h3>Autowired Constructors</h3>
 * <p>Only one constructor of any given bean class may declare this annotation with the
 * {@link #required} attribute set to {@code true}, indicating <i>the</i> constructor
 * to autowire when used as a Spring bean. Furthermore, if the {@code required}
 * attribute is set to {@code true}, only a single constructor may be annotated
 * with {@code @Autowired}. If multiple <i>non-required</i> constructors declare the
 * annotation, they will be considered as candidates for autowiring. The constructor
 * with the greatest number of dependencies that can be satisfied by matching beans
 * in the Spring container will be chosen. If none of the candidates can be satisfied,
 * then a primary/default constructor (if present) will be used. Similarly, if a
 * class declares multiple constructors but none of them is annotated with
 * {@code @Autowired}, then a primary/default constructor (if present) will be used.
 * If a class only declares a single constructor to begin with, it will always be used,
 * even if not annotated. An annotated constructor does not have to be public.
 *
 * <h3>Autowired Fields</h3>
 * <p>Fields are injected right after construction of a bean, before any config methods
 * are invoked. Such a config field does not have to be public.
 *
 * <h3>Autowired Methods</h3>
 * <p>Config methods may have an arbitrary name and any number of arguments; each of
 * those arguments will be autowired with a matching bean in the Spring container.
 * Bean property setter methods are effectively just a special case of such a general
 * config method. Such config methods do not have to be public.
 *
 * <h3>Autowired Parameters</h3>
 * <p>Although {@code @Autowired} can technically be declared on individual method
 * or constructor parameters since Spring Framework 5.0, most parts of the
 * framework ignore such declarations. The only part of the core Spring Framework
 * that actively supports autowired parameters is the JUnit Jupiter support in
 * the {@code spring-test} module (see the
 * <a href="TestContext'" DESIGNTIMESP=2532>https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-di">TestContext framework</a>
 * reference documentation for details).
 *
 * <h3>Multiple Arguments and 'required' Semantics</h3>
 * <p>In the case of a multi-arg constructor or method, the {@link #required} attribute
 * is applicable to all arguments. Individual parameters may be declared as Java-8 style
 * {@link java.util.Optional} or, as of Spring Framework 5.0, also as {@code @Nullable}
 * or a not-null parameter type in Kotlin, overriding the base 'required' semantics.
 *
 * <h3>Autowiring Arrays, Collections, and Maps</h3>
 * <p>In case of an array, {@link java.util.Collection}, or {@link java.util.Map}
 * dependency type, the container autowires all beans matching the declared value
 * type. For such purposes, the map keys must be declared as type {@code String}
 * which will be resolved to the corresponding bean names. Such a container-provided
 * collection will be ordered, taking into account
 * {@link org.springframework.core.Ordered Ordered} and
 * {@link org.springframework.core.annotation.Order @Order} values of the target
 * components, otherwise following their registration order in the container.
 * Alternatively, a single matching target bean may also be a generally typed
 * {@code Collection} or {@code Map} itself, getting injected as such.
 *
 * <h3>Not supported in {@code BeanPostProcessor} or {@code BeanFactoryPostProcessor}</h3>
 * <p>Note that actual injection is performed through a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor
 * BeanPostProcessor} which in turn means that you <em>cannot</em>
 * use {@code @Autowired} to inject references into
 * {@link org.springframework.beans.factory.config.BeanPostProcessor
 * BeanPostProcessor} or
 * {@link org.springframework.beans.factory.config.BeanFactoryPostProcessor BeanFactoryPostProcessor}
 * types. Please consult the javadoc for the {@link AutowiredAnnotationBeanPostProcessor}
 * class (which, by default, checks for the presence of this annotation).
 *
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @author Sam Brannen
 * @since 2.5
 * @see AutowiredAnnotationBeanPostProcessor
 * @see Qualifier
 * @see Value
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

 /**
  * Declares whether the annotated dependency is required.
  * <p>Defaults to {@code true}.
  */
 boolean required() default true;

}

​

其中这里写到

In case of an array, java.util.Collection, or java.util.Map dependency type, the container autowires all beans matching the declared value type. For such purposes, the map keys must be declared as type String which will be resolved to the corresponding bean names.

翻译过来。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

NASA和IBM联合开发的 2022 年多时相土地分类数据集

简介 美国国家航空航天局&#xff08;NASA&#xff09;和国际商业机器公司&#xff08;IBM&#xff09;合作&#xff0c;利用大规模卫星和遥感数据&#xff0c;包括大地遥感卫星和哨兵-2 号&#xff08;HLS&#xff09;数据&#xff0c;创建了地球观测人工智能基础模型。通过奉…

【Windows】解决Windows磁盘有锁和感叹号方法

文章目录 1、概述2、效果3、解决方案3.1、先看自己电脑环境3.2、查看BitLocker情况3.3、查看设备加密 4、其他方案5、BitLocker5.1、BitLocker 是什么5.2、BitLocker 作用5.3、BitLocker 和 TPM 1、概述 目前在整理自己新电脑的软件&#xff0c;无意间电脑磁盘有锁和感叹号的标…

Dynamic Wallpaper v17.4 mac版 动态视频壁纸 兼容 M1/M2

Dynamic Wallpaper Engine 是一款适用于 Mac 电脑的视频动态壁纸&#xff0c; 告别单调的静态壁纸&#xff0c;拥抱活泼的动态壁纸。内置在线视频素材库&#xff0c;一键下载应用&#xff0c;也可导入本地视频&#xff0c;同时可以将视频设置为您的电脑屏保。 应用介绍 Dynam…

多线程案例及常用模式

一.单例模式——经典的设计模式 什么是单例模式&#xff1a;就是规定一个类只能创建一个对象&#xff0c;也就是保证某个类在程序中只存在唯一一个实例&#xff0c;而不会创建出多个实例 根据对象创建的时机不同&#xff0c;可以分为饿汉模式和懒汉模式 1.饿汉模式 在类加载…

2024.3.12 C++

1、自己封装一个矩形类(Rect)&#xff0c;拥有私有属性:宽度(width)、高度(height) 定义公有成员函数初始化函数:void init(int w, int h)更改宽度的函数:set w(int w)更改高度的函数:set h(int h)输出该矩形的周长和面积函数:void show() #include <iostream>using nam…

动手学深度学习-注意力机制Transformer

注意力机制 1. 注意力提示 1.1. 生物学中的注意力提示 **自主性提示&#xff08;随意线索&#xff09;&#xff1a;收到认知和意识的控制&#xff0c;有主观意愿的推动。**如下图&#xff0c;所有纸制品都是黑白印刷的&#xff0c;但咖啡杯是红色的。 换句话说&#xff0c;这…

【图像超分】论文复现:Pytorch实现FSRCNN,包含详细实验流程和与SRCNN的比较

文章目录 前言1. FSRCNN网络结构2. 训练FSRCNN3. FSRCNN模型测试4. 训练好的FSRCNN模型超分自己的图像 前言 论文地址&#xff1a;Accelerating the Super-Resolution Convolutional Neural Network 论文精读&#xff1a; 请配合上述论文精读文章使用&#xff0c;效果更佳&…

Python接口自动化核心模块 - 数据库操作和日志

一、Python连接数据库常见模块 MysqlDBpython2时代最火的驱动库。基于C开发&#xff0c;对windows平台不友好。现在已经进入python3时代&#xff0c;基本不再使用MysqlClientmysqldb的衍生版本&#xff0c;完全兼容python3.它是重量级Web开发框架Django中ORM功能依赖工具Pymys…

01_lombok review

文章目录 Lombok父子工程ide中的Maven基础配置前置知识储备 Lombok 怎么引入Lombok依赖&#xff1a; step1&#xff1a;引入Lombok依赖 eg&#xff1a; <dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok<…

9:00面试,9:06就出来了,问的实在是太变态了

我从一家小公司转投到另一家公司&#xff0c;期待着新的工作环境和机会。然而&#xff0c;新公司的加班文化让我有些始料未及。虽然薪资相对较高&#xff0c;但长时间的工作和缺乏休息使我身心俱疲。 就在我逐渐适应这种高强度的工作节奏时&#xff0c;公司突然宣布了一则令人…

GaussianEditor:根据用户指令编辑三维 GS 场景

Paper: Fang J, Wang J, Zhang X, et al. Gaussianeditor: Editing 3d gaussians delicately with text instructions[J]. arXiv preprint arXiv:2311.16037, 2023. Introduction: https://gaussianeditor.github.io/ Code: Unreleased 本篇的 GaussianEditor 和 NTU 的 Gaussi…

《父母的语言:3000万词汇塑造更强大的学习型大脑》早期家庭语言环境的重要性(二)

目录 简介 经典内容摘录 简介 本书作者是美国芝加哥大学妇科及儿科教授达娜萨斯金德博士。作者发起了“3000万词汇倡议”&#xff0c;“3000万词汇倡议”发现了一个秘密&#xff0c;即低收入家庭的孩子为什么“输在起跑线”上。调查显示&#xff0c;低收入家庭…

【零基础学习03】嵌入式linux驱动中自旋锁功能基本实现

大家好,为了进一步提升大家对实验的认识程度,每个控制实验将加入详细控制思路与流程,欢迎交流学习。 今天给大家分享一下,linux系统里面自旋锁操作的具体实现,操作硬件为I.MX6ULL开发板。 第一:自旋锁基本简介 ①、自旋锁保护的临界区要尽可能的短,可以使用一个变量来表…

119.龙芯2k1000-pmon(18)-全自动安装linux系统

经过两天的测试和完善&#xff0c;现在基本已经正常可用了。 &#xff08;全自动是假&#xff0c;接近全自动吧。&#xff09; 需要使用配测电脑的网络功能&#xff0c;windows即可&#xff0c;脱离linux虚拟机。&#xff08;理论上讲u盘也是可以的&#xff09; 测试平台&…

JDBC底层原理

1、什么是JBDC? JBDC&#xff08;Java Database Connectivity&#xff09;&#xff0c;JDBC只是一套规范接口&#xff0c;真正实现的是各数据库厂商驱动。 2、JBDC的底层的主要接口对象是什么&#xff1f; JBDC的底层主要是三个接口对象,Connection、Statement、ResultSet。Co…

C#实现二分查找算法

C#实现二分查找算法 以下是一个使用 C# 实现的二分查找算法示例&#xff1a; using System;class Program {static int BinarySearch(int[] arr, int target){int low 0;int high arr.Length - 1;while (low < high){int mid (low high) / 2;// 如果目标值等于中间元素…

javaEE6(网站第3章-jsp练习中三个例题动手做一遍;课后题2(1),(2))

两个数求和 用javascript实现。 输入、处理、输出用同一个页面(自己处理自己)。 输入1.jsp&#xff0c;处理和输出2.jsp。 &#xff08;4&#xff09;输入1.jsp&#xff0c;处理2.jsp&#xff0c;处理完转回1.jsp显示结果。 &#xff08;5&#xff09;输入1.jsp&#xff0c;处…

Python: 如何绘制核密度散点图和箱线图?

01 数据样式 这是数据样式&#xff1a; 要求&#xff08;我就懒得再复述一遍了&#xff0c;直接贴图&#xff09;&#xff1a; Note&#xff1a;数据中存在无效值NA&#xff08;包括后续的DEM&#xff09;&#xff0c;需要注意 02 提取DEM 这里我就使用gdal去提取一下DEM列…

Mixamo动画素材导入UE5的最简单方法

一、Mixamo素材 官网&#xff1a;https://www.mixamo.com/ Mixamo是Adobe公司出品的免费动画库&#xff0c;可商用。软件分为characters(角色&#xff09;、Animations&#xff08;动画)两个部分。 二、辅助工具MIXAMO CONVERTER 官网&#xff1a;https://terribilisstudio…

海外媒体发稿:新闻媒体发稿7种方法-华媒舍

新闻报道媒体发稿营销推广是当代企业形象宣传的重要手段之一&#xff0c;合理推广可以提升品牌知名度、吸引住潜在用户。在这篇文章中&#xff0c;我们将要详细介绍七种科学合理的形式&#xff0c;帮助你完全把握新闻报道媒体发稿营销推广。 1.明确目标群体明确目标群体是实现推…