首页 > 其他分享 >Spring中使用自带@Autowired注解实现策略模式

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

时间:2024-03-12 15:12:45浏览次数:20  
标签:code java Autowired Spring link 自带 annotation

场景

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

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/130503707

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

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127622238

上面在讲策略模式具体在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值则为对应的策略实现类。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

实现

其实不光是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.

翻译过来。

 

标签:code,java,Autowired,Spring,link,自带,annotation
From: https://www.cnblogs.com/badaoliumangqizhi/p/18068347

相关文章

  • 【2024面试刷题】二、Spring Cloud 面试题之Hystrix
    1、springcloud断路器的作用是什么?答:当一个服务调用另一个服务由于网络原因或自身原因出现问题时,调用者将等待被调用者的响应当更多的服务要求这些资源导致更多的请求等待时,就会出现连锁效应(雪崩效应)。断路器完全打开:一段时间内达到一定次数不能调用并且多次监测无恢复迹象......
  • SpringBoot自定义validation注解校验参数只能为指定的值
    需求:实体类中某个属性的值必须为指定的值,比如0或者1SpringBoot版本:2.4.8validation 依赖<!--数据校验--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId></dependency>......
  • Spring状态机(FSM),让订单状态流转如丝般顺滑
    引言在复杂的应用程序设计中,尤其是那些涉及多个状态变迁和业务流程控制的场景,有限状态机(FiniteStateMachine,FSM)是一种强大而有效的建模工具。Spring框架为此提供了Spring状态机(SpringStateMachine)这一组件,它允许开发者以一种声明式且结构清晰的方式来管理和控制对象的状态......
  • springBoot
    **Springboot**的主要优点:为所有spring开发者更快的入门开箱即用,提供各种默认配置来简化项目配置内嵌式容器简化web项目没有冗余代码生成和xml配置的要求MVCMVVM微服务架构微服务是一种架构可以把原先是一个整体的模块进行拆分成小模块去进行操作,其不会对其整体模块进行......
  • k01创建第一个springboot程序
    创建springboot程序的方式有两种1、在spring官网创建,https://start.spring.io/2、使用idea程序创建。一般情况下我们都是使用idea软件创建的,因为这样会更方便1、使用spring官网创建(SpringInitializr)(初学使用)(一般不用)我们只需要在网站上输入(https://start.spring.i......
  • Spring多线程事务处理
    一、背景本文主要介绍了spring多线程事务的解决方案,心急的小伙伴可以跳过上面的理论介绍分析部分直接看最终解决方案。在我们日常的业务活动中,经常会出现大规模的修改插入操作,比如在3.0的活动赛事创建,涉及到十几张表的插入(一张表可能插入一行或者多行数据),由于单线程模型的关系,......
  • [springboot] SpringBoot启动成功后因actuator健康检测报:Redis health check failed/
    0序背景:项目中引入了spring-boot-starter-actuator健康检测模块<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>1问题描述确认微服务刚启动后,因K8S集群周期性定时(默认每隔1......
  • spring-事务案例
    spring的案例场景同一个事务中使用并发操作导致更新获取锁失败@AutowiredServiceservice1;@TransactionalpublicvoidmethodA(){ List<Object>objs; service1.deleteByid(id1); objs.parallelStream().forEach(o->{ UserEntityusEntity=newUserEntity();......
  • SpringBoot自动配置原理解析
    一、什么是SpringBoot自动配置首先介绍一下什么是SpringBoot,SpringBoost是基于Spring框架开发出来的功能更强大的Java程序开发框架,其最主要的特点是:能使程序开发者快速搭建一套开发环境。SpringBoot能将主流的开发框架(例如SpringMVC,Dubbo,Mybatis,Redis等),做到像Maven导......
  • springboot初始化时执行方法
    参考:http://www.360doc.com/content/23/0303/15/81790262_1070284511.shtml监听容器刷新完成扩展点ApplicationListener<ContextRefreshedEvent>ApplicationContext事件机制是观察者设计模式实现的,通过ApplicationEvent和ApplicationListener这两个接口实现ApplicationContext......