Spring 依赖注入

Spring中装配Bean有三种方式:

  • 在xml中显示配置
  • 在Java中显示配置
  • 隐式的Bean自动发现和装配

  (显示配置和组件扫描可以同时使用)

一、隐式的Bean自动发现和装配
  两步: 组件扫描(component scanning)
      自动装配(autowiring)
1.组件扫描
  1.1 组件扫描默认不开启,开启方式:
  (1)在xml配置文件中添加元素<context:component-scan base-package="指定扫描的包"/>

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:component-scan base-package="com.huawei.cbc.cloudbi.test"/>

</beans>

  (2)在Java配置类中上添加注解@ComponetScan,默认扫描与配置类相同的包,可以设置成其他包,比如@ComponetScan(base-packages={"soundsystem","hello"})

@Configuration
@ComponetScan
public class ConfigClass{}

  

  1.2 要想将某个类声明为bean,我们只需要在该类上添加注解@Component。

  @Component是一个通用的Spring容器管理的单例bean组件,而@Repository, @Service, @Controller是针对不同的使用场景所采取的特定功能化的注解组件。具体区别见https://blog.csdn.net/fansili/article/details/78740877

2. 自动装配
  
2.1 使用注解@Autowired和@Resource
    两者区别见https://baijiahao.baidu.com/s?id=1608114169828948852&wfr=spider&for=pc

二、通过Java代码装配Bean

  1. 声明bean

   在Java配置类中声明bean,只需要编写一个方法,这个方法会创建所需类型的实例,然后给这个方法添加@Bean注解

@Configuration
public class BeanConfig
{
    @Bean
    public BeanThree getBeanThree()
    {
        return new BeanThree();
    }
}

   默认情况下,bean的ID与带有@Bean注解的方法一致,这里bean的ID就是getBeanThree。如需修改,可以通过name指定一个不同的名字:@Bean(name="Three")

原文地址:https://www.cnblogs.com/langren1992/p/9782847.html