SpringBoot通过注解注入Bean的几种方式解析

目录
  • 1、背景
    • xml扫描包的方式
  • 2、通过注解注入的一般形式
    • 2.1、Bean类
    • 2.2、Configuration类
    • 2.3、Test类
  • 3、通过构造方法注入Bean
    • 3.1、Bean类
    • 3.2、AnotherBean类
    • 3.3、Configuration类
  • 4、通过set方法注入Bean
    • 4.1、MyBean类
    • 4.2、Configuration类和Test类
  • 5、通过属性去注入Bean
  • 6、通过List注入Bean
    • 6.1、MyBeanList类
    • 6.2、MyConfiguration类
    • 6.3、MyConfiguration类
  • 7、通过Map去注入Bean

1、背景

我们谈到Spring的时候一定会提到IOC容器、DI依赖注入,Spring通过将一个个类标注为Bean的方法注入到IOC容器中,达到了控制反转的效果。那么我们刚开始接触Bean的时候,一定是使用xml文件,一个一个的注入,就例如下面这样。

 <bean id="bean" class="com.xxx.xxx.Bean" />

我们的项目一般很大的话,就需要成千上百个Bean去使用,这样写起来就很繁琐。那么Spring就帮我们实现了一种通过注解来实现注入的方法。只需要在你需要注入的类前面加上相应的注解,Spring就会帮助我们扫描到他们去实现注入。

xml扫描包的方式

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

2、通过注解注入的一般形式

一般情况下,注入Bean有一个最直白,最易懂的方式去实现注入,下面废话先不多说,先贴代码。

2.1、Bean类

 public class MyBean{
 }

2.2、Configuration类

//创建一个class配置文件
@Configuration
public class MyConfiguration{
//将一个Bean交由Spring进行管理
    @Bean
    public MyBean myBean(){
        return new MyBean();
    }
}

2.3、Test类

与xml有一点不同,这里在Test中,实例化的不再是ClassPathXmlApplicationContext,而是获取的AnnotationConfigApplicationContext实例。

ApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class);
MyBean myBean = cotext.getBean("myBean",MyBean.class);
System.out.println("myBean = " + myBean);

上面的代码中MyBean也就是我们需要Spring去管理的一个Bean,他只是一个简单的类。而MyConfiguration中,我们首先用@Configuration注解去标记了该类,这样标明该类是一个Spring的一个配置类,在加载配置的时候会去加载他。

在MyConfiguration中我们可以看到有一个方法返回的是一个MyBean的实例,并且该方法上标注着@Bean的注解,标明这是一个注入Bean的方法,会将下面的返回的Bean注入IOC。

3、通过构造方法注入Bean

我们在生成一个Bean实例的时候,可以使用Bean的构造方法将Bean实现注入。直接看代码

3.1、Bean类

 @Component
 public class MyBeanConstructor {
     private AnotherBean anotherBeanConstructor;
     @Autowired
     public MyBeanConstructor(AnotherBean anotherBeanConstructor){
         this.anotherBeanConstructor = anotherBeanConstructor;
     }
     @Override
     public String toString() {
         return "MyBean{" +
             "anotherBeanConstructor=" + anotherBeanConstructor +
             '}';
     }
 }

3.2、AnotherBean类

 @Component(value="Bean的id,默认为类名小驼峰")
 public class AnotherBean {
 }

3.3、Configuration类

 @Configuration
 @ComponentScan("com.company.annotationbean")
 public class MyConfiguration{
 }

这里我们可以发现,和一般方式注入的代码不一样了,我们来看看新的注解都是什么意思:

@AutoWired

简单粗暴,直接翻译过来的意思就是自动装配:wrench:,还不理解为什么叫自动装配:wrench:?看了下一个注解的解释你就知道了。若是在这里注入的时候指定一个Bean的id就要使用@Qualifier注解

@Component(默认单例模式)

什么??这翻译过来是零件,怎么感觉像是修汽车??是的,Spring管理Bean的方法就是修汽车的方式。我们在需要将一个类变成一个Bean被Spring可以注入的时候加上注解零件@Conmonent,那么我们就可以在加载Bean的时候把他像零件一样装配:wrench:到这个IOC汽车上了

在这里我们还有几个其他的注解也可以实现这个功能,也就是细化的@Component:

@Controller 标注在Controller层

@Service 标注在Service层

@Repository 标注在dao层

@ComponentScan("")

还是翻译,零件扫描,我们去看看括号里的“零件仓库”里面,哪些“零件”(类)需要被装载,Spring就会去扫描这个包,将里面所有标注了@Component的类进行注入。

这里的通过构造方法进行注入就很好理解了,我们在装配MyBean这个零件的时候,突然发现他必须在AnotherBean的基础上才能安装到IOC里面,那么我们就在每次装配MyBean的时候自动装配:wrench:一个AnotherBean进去。举个:chestnut:吧:

还是以汽车为例,我们在踩油门出发之前,是不是必须发车??这里的AutoWired的内容就像发车,你不发车,这个油门你踩断都没有用,他都不会走。

4、通过set方法注入Bean

我们可以在一个属性的set方法中去将Bean实现注入,看代码吧

4.1、MyBean类

 @Component
 public class MyBeanSet {
     private AnotherBean anotherBeanSet;
     @Autowired
     public void setAnotherBeanSet(AnotherBean anotherBeanSet) {
         this.anotherBeanSet = anotherBeanSet;
     }
     @Override
     public String toString() {
         return "MyBeanSet{" +
             "anotherBeanSet=" + anotherBeanSet +
             '}';
     }
 }

4.2、Configuration类 和 Test类

同上一个,就不贴了

这里我们发现在setter方法上我们有一个@AutoWired,与上面不同的是,我们不会在实例化该类时就自动装配:wrench:这个对象,而是在显式调用setter的时候去装配。

5、通过属性去注入Bean

我们前面两种注入的方式诸如时间不同,并且代码较多,若是通过属性,即就是

 @Component
 public class MyBeanProperty {
     @Autowired
     private AnotherBean anotherBeanProperty;
     @Override
     public String toString() {
         return "MyBeanProperty{" +
             "anotherBeanProperty=" + anotherBeanProperty +
             '}';
     }
 }

这里我们可以看到我们这个类中需要使用AnotherBean这个实例对象,我们可以通过@AutoWired去自动装配它。

6、通过List注入Bean

6.1、MyBeanList类

 @Component
 public class MyBeanList {
     private List<String> stringList;
     @Autowired
     public void setStringList(List<String> stringList) {
         this.stringList = stringList;
     }
     public List<String> getStringList() {
         return stringList;
     }
 }

6.2、MyConfiguration类

 @Configuration
 @ComponentScan("annoBean.annotationbean")
 public class MyConfiguration {
     @Bean
     public List<String> stringList(){
        List<String> stringList = new ArrayList<String>();
         stringList.add("List-1");
         stringList.add("List-2");
         return stringList;
     }
 }

这里我们将MyBeanList进行了注入,对List中的元素会逐一注入。下面介绍另一种方式注入List

6.3、MyConfiguration类

@Bean
//通过该注解设定Bean注入的优先级,不一定连续数字
@Order(34)
public String string1(){
    return "String-1";
}
@Bean
@Order(14)
public String string2(){
    return "String-2";
}

注入与List中泛型一样的类型,会自动去匹配类型,及时这里没有任何List的感觉,只是String的类型,但他会去通过List的Bean的方式去注入。

第二种方式的优先级高于第一种,当两个都存在的时候,若要强制去使用第一种方式,则要去指定Bean的id即可

7、通过Map去注入Bean

 @Component
 public class MyBeanMap {
     private Map<String,Integer> integerMap;
     public Map<String, Integer> getIntegerMap() {
         return integerMap;
     }
     @Autowired
     public void setIntegerMap(Map<String, Integer> integerMap) {
         this.integerMap = integerMap;
     }
 }
 @Bean
    public Map<String,Integer> integerMap(){
        Map<String,Integer> integerMap = new HashMap<String, Integer>();
        integerMap.put("map-1",1);
        integerMap.put("map-2",2);
        return integerMap;
    }
    @Bean
    public Integer integer1(){
        return 1;
    }
    @Bean
    public Integer integer2(){
        return 2;
    }

同样这里也具有两种方式去注入Map类型Bean,且第二种的优先值高于第一种

以上就是Bean通过注解注入的几种方式,大家可以对比着xml注入的方式去看。

希望大家以后多多支持我们!

(0)

相关推荐

  • Spring注入值到Bean的三种方式

    在Spring中,有三种方式注入值到 bean 属性. 正常的方式 快捷方式 "p" 模式 新建一个User类,它包含username和password两个属性,现在使用spring的IOC注入值到该bean. package com.example.pojo; public class User { private String username; private String password; public String getUsername() { return userna

  • 详解SpringBoot静态方法获取bean的三种方式

    目录 方式一  注解@PostConstruct 方式二  启动类ApplicationContext 方式三 手动注入ApplicationContext 方式一  注解@PostConstruct import com.example.javautilsproject.service.AutoMethodDemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springfr

  • 关于spring boot中几种注入方法的一些个人看法

    前言 最近在知乎上面看到一篇关于程序员面试的问题,面试官问我们一般有几种注入的方法,这几种注入的方法分别在什么时候运用比合理,当时我看到这个时候懵逼了,由于我自己也是刚刚接触springboot不久,所以就自己在平时运用的上面总结了一些知识点常用的几种springboot的注入方法,由于我是一个小萌新,所只要是能够起道注入的方法的注解我都列出来,有可能会有错,希望大家能够及时提出来我来解决: @Autowired @Resource @Component @Configuration @Qual

  • 详谈spring boot中几种常见的依赖注入问题

    目录 @Autowired依赖注入问题–逻辑使用先于@Autowired注解处理 测试用例 BeanFactory.getBean问题–getBean调用先于BeanDefinition信息注册 在Configuration中使用@Autowired注解 spring 实例化Bean过程 @Bean内部使用配置类@Autowired注解引入依赖 InitializingBean#afterPropertiesSet内部使用依赖 总结 最近有空总结一下之前在使用spring boot时遇到过的几种

  • SpringBoot注入配置文件的3种方法详解

    这篇文章主要介绍了SpringBoot注入配置文件的3种方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 方案1:@ConfigurationProperties+@Component 定义spring的一个实体bean装载配置文件信息,其它要使用配置信息是注入该实体bean /** * 将配置文件中配置的每一个属性的值,映射到这个组件中 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配

  • SpringBoot通过注解注入Bean的几种方式解析

    目录 1.背景 xml扫描包的方式 2.通过注解注入的一般形式 2.1.Bean类 2.2.Configuration类 2.3.Test类 3.通过构造方法注入Bean 3.1.Bean类 3.2.AnotherBean类 3.3.Configuration类 4.通过set方法注入Bean 4.1.MyBean类 4.2.Configuration类和Test类 5.通过属性去注入Bean 6.通过List注入Bean 6.1.MyBeanList类 6.2.MyConfiguration类

  • Spring为IOC容器注入Bean的五种方式详解

    这篇文章主要介绍了Spring为IOC容器注入Bean的五种方式详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一 @Import导入组件,id默认是组件的全类名 //类中组件统一设置.满足当前条件,这个类中配置的所有bean注册才能生效: @Conditional({WindowsCondition.class}) @Configuration @Import({Color.class,Red.class,MyImportSelector

  • 详解Spring通过@Value注解注入属性的几种方式

    场景 假如有以下属性文件dev.properties, 需要注入下面的tag tag=123 通过PropertyPlaceholderConfigurer <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="dev.properties" /&

  • Springboot实现多线程注入bean的工具类操作

    场景: 使用springboot多线程,线程类无法自动注入需要的bean 解决方法: 通过工具类获取需要的bean 工具类代码: import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springfram

  • SpringBoot @GroupSequenceProvider注解实现bean多属性联合校验的示例代码

    目录 参考资料 一. 前期准备 二. 需求 三. 需求 参考资料 分组序列@GroupSequenceProvider.@GroupSequence控制数据校验顺序,解决多字段联合逻辑校验问题[享学Spring MVC] Hibernate Validator提供了非标准的@GroupSequenceProvider注解.针对当前对象实例的状态,动态来决定加载那些校验组进入默认校验组.需要借助Hibernate Validation提供给我们的DefaultGroupSequenceProvid

  • 基于spring三方包类注入容器的四种方式小结

    如果引用第三方jar包,肯定是不能直接使用常用注解@Controller.@Service.@Repository.@Component将类的实例注入到spring容器中.以下四种方法可以向spring容器中导入三方包中类实例 . 1 xml配置 这种情况大家用的比较多,就是在spring的xml文件中配置需要导入的bean.在springweb项目工程web.xml中 ContextLoaderListener或者DispatcherServlet的初始参数contextConfigLocat

  • 浅谈SpringBoot资源初始化加载的几种方式

    目录 一.问题 二.资源初始化 一.问题 在平时的业务模块开发过程中,难免会需要做一些全局的任务.缓存.线程等等的初始化工作,那么如何解决这个问题呢?方法有多种,但具体又要怎么选择呢? 二.资源初始化 1.既然要做资源的初始化,那么就需要了解一下springboot启动过程(这里大体说下启动过程,详细:https://www.jb51.net/article/133648.htm) 按照前面的分析,Spring-boot容器启动流程总体可划分为2部分: 执行注解:扫描指定范围下的bean.载入自

  • spring boot 注入 property的三种方式(推荐)

    以前使用spring的使用要注入property要配置PropertyPlaceholder的bean对象.在springboot除  了这种方式以外还可以通过制定 配置ConfigurationProperties直接把property文件的 属性映射到 当前类里面. @ConfigurationProperties(prefix = "mypro", merge = true, locations = { "classpath:my.properties" })

  • SpringBoot 中实现跨域的5种方式小结

    一.为什么会出现跨域问题 出于浏览器的同源策略限制.同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响.可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现. 同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互.所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port) 二.什么是跨域 当一个请求url的协议

随机推荐