原课程:通过注解注入Bean

注入bean知识点思维导图

【Spring 基础】通过注解注入Bean

Spring 4.x推荐使用基于构造器的方式进行bean注入7.4.1 Dependency Injection
spring为什么推荐使用构造器注入

通过构造器和Set方法注入Bean

【Spring 基础】通过注解注入Bean
注意:通过构造器注入Bean时,如果只有一个构造器,可以不写@Autowired注解,详见17. Spring Beans and Dependency Injection


The following example shows a @Service Bean that uses constructor injection to obtain a required RiskAssessor bean:

package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	@Autowired
	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}

	// ...

}

If a bean has one constructor, you can omit the @Autowired, as shown in the following example:

@Service
public class DatabaseAccountService implements AccountService {

	private final RiskAssessor riskAssessor;

	public DatabaseAccountService(RiskAssessor riskAssessor) {
		this.riskAssessor = riskAssessor;
	}

	// ...

}

通过属性直接注入Bean

【Spring 基础】通过注解注入Bean

实例化和注入时指定Bean的ID
【Spring 基础】通过注解注入Bean

List/Set注入

直接注入List实例
【Spring 基础】通过注解注入Bean
将多个泛型实例注入到List
【Spring 基础】通过注解注入Bean

Map注入

直接注入Map实例
【Spring 基础】通过注解注入Bean

将多个泛型实例注入到Map
【Spring 基础】通过注解注入Bean

把某个类型的bean组成一个Map或者List注入到另一个bean中,可以使用@Autowired或@Resource实现。
springboot注入@autowire——Map/List

Integer等包装类型直接赋值

【Spring 基础】通过注解注入Bean

Spring IoC容器内置接口实例注入

【Spring 基础】通过注解注入Bean

相关文章:

  • 2021-04-04
  • 2021-04-23
  • 2021-05-25
  • 2021-05-21
  • 2021-04-03
  • 2019-12-05
  • 2021-06-29
  • 2021-10-05
猜你喜欢
  • 2021-09-22
  • 2022-12-23
  • 2021-05-30
  • 2021-11-20
  • 2021-12-01
  • 2021-08-24
相关资源
相似解决方案