Spring IoC 依赖注入(一)使用说明

Spring IoC 依赖注入(一)使用说明

Spring 核心编程思想目录:https://www.cnblogs.com/binarylei/p/12290153.html

1. 依赖注入方法

1.1 Setter 方法依赖注入

  • 手动模式

    • XML 资源配置元信息

      <bean id="beanA" class="com.binarylei.spring.ioc.injection.BeanA">
          <property name="beanB" ref="beanB"/>
      </bean>
      
    • Java 注解配置元信息

      @Bean
      public BeanB beanB() {
          return new BeanB();
      }
      
    • API 配置元信息

      @Test
      public void testSettingInjectByApi() {
          DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
          beanFactory.registerBeanDefinition("beanB", new RootBeanDefinition(BeanB.class));
          beanFactory.registerBeanDefinition("beanA", BeanDefinitionBuilder
                                             .rootBeanDefinition(BeanA.class)
                                             .addPropertyReference("beanB", "beanB")
                                             .getBeanDefinition());
      
          BeanA beanA = beanFactory.getBean(BeanA.class);
          Assert.assertNotNull(beanA.getBeanB());
      }
      
  • 自动模式(只有 XML 配置方式,不推荐)

    • byName

      <bean id="beanA" class="com.binarylei.spring.ioc.injection.BeanA" autowire="byName"/>
      
    • byType

      <bean id="beanA" class="com.binarylei.spring.ioc.injection.BeanA" autowire="byType"/>
      

1.2 构造器依赖注入

  • 手动模式

    • XML 资源配置元信息

      <bean id="beanA" class="com.binarylei.spring.ioc.injection.BeanA">
          <constructor-arg name="beanB" ref="beanB"/>
      </bean>
      
    • Java 注解配置元信息

      @Bean
      public BeanA beanA(BeanB beanB, BeanFactory beanFactory) {
          return new BeanA(beanB, beanFactory);
      }
      
    • API 配置元信息

      @Test
      public void testInjectConstructorByApi() {
          DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
          beanFactory.registerBeanDefinition("beanB", new RootBeanDefinition(BeanB.class));
          beanFactory.registerBeanDefinition("beanA", BeanDefinitionBuilder
                                             .rootBeanDefinition(BeanA.class)
                                             .addConstructorArgReference("beanB")
                                             .getBeanDefinition());
      
          BeanA beanA = beanFactory.getBean(BeanA.class);
          Assert.assertNotNull(beanA.getBeanB());
      }
      
  • 自动模式(只有 XML 配置方式,不推荐)

    • constructor:constructor 本质是使用 byType 进行注入

      <bean id="beanA" class="com.binarylei.spring.ioc.injection.BeanA" autowire="constructor"/>
      

1.3 字段注入

  • 手动模式 - Java 注解配置元信息
    • @Autowired
    • @Resource
    • @Inject(可选)
@Autowired
private BeanB beanB;
@Inject
private BeanB beanB2;
@Resource
private BeanFactory beanFactory;

引入 jsr330 maven 规范:

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

Java EE CDI Dependency Injection (@Inject) tutorial

1.4 方法注入

  • 手动模式 - Java 注解配置元信息
    • @Autowired
    • @Resource
    • @Inject(可选)
    • @Bean
private BeanB beanB;
private BeanB beanB2;
private BeanFactory beanFactory;

@Autowired
public void init1(BeanB beanB) {
    this.beanB = beanB;
}
@Inject
public void init2(BeanB beanB2) {
    this.beanB2 = beanB2;
}
@Resource
public void init3(BeanFactory beanFactory) {
    this.beanFactory = beanFactory;
}

1.5 回调注入

BeanFactoryAware ...

public class InjectCallbackTest implements BeanFactoryAware {
    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }
}

2. 依赖注入类型

2.1 基础类型注入

  • 原生类型(Primitive ): boolean、byte、char、short、int 、float、long、double
  • 标量类型(Scalar ): Number、Character、Boolean、Enum、Locale、Charset、Currency、Properties、UUID
  • 常规类型(General ): Object、String、Timezone、Calendar、Optional
  • Spring 类型:Resource、Inputsource、Formatter
@Value("1")
private long num;

@Value("#{1 + 2}")
private long num2;

@Value("${user.dir}")
private String userDir;

@Autowired
private Optional<Environment> environmentOptional;

@Value("com/binarylei/spring/ioc/injection/spring-dependency-inject-constructor.xml")
private Resource resource;

2.3 集合类型注入

  • 数组类型(Array ):原生类型、标量类型、常规类型、 Spring 类型
  • 集合类型(Collection )
    • Collection:List、Set(Sortedset、 NavigableSet、 EnumSet)
    • Map:Properties
@Autowired
private Environment[] environmentArr;
@Autowired
private List<Environment> environmentList;
@Autowired
private Map<String, Environment> environmentMap;

2.4 限定注入

  • 使用注解 @Qualifier 限定

    • 通过 Bean 名称限定

      @Autowired
      @Qualifier("uri2")
      private URI uri2;
      
    • 通过分组限定

      // 使用
      @Autowired
      @Qualifier
      private URI uri5;
      
      // 配置
      @Bean
      @Qualifier
      public URI uri3() {
          return URI.create("http://www.tian.com");
      }
      
      
  • 基于注解 @Qualifier 扩展限定

    • 自定义注解 - 如 Spring Cloud @Loadbalanced

      // 使用,自动按组注入
      @Autowired
      @Group1
      private URI uri3;
      
      @Autowired
      @Group2
      private URI uri4;
      
      // 配置
      @Bean
      @Primary
      @Group1
      public URI uri1() {
          return URI.create("http://www.baidu.com");
      }
      @Bean
      @Group2
      public URI uri2() {
          return URI.create("http://www.qq.com");
      }
      
      // 定义注解
      @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
      @Retention(RetentionPolicy.RUNTIME)
      @Inherited
      @Qualifier
      private static @interface Group1 {
      }
      @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
      @Retention(RetentionPolicy.RUNTIME)
      @Inherited
      @Qualifier
      private static @interface Group2 {
      }
      
      

3. 延迟依赖注入

  • 使用注解 @Lazy 限定
  • ObjectProvider 或 ObjectFactory
@Autowired
private ObjectProvider<Environment> environmentObjectProvider;

@Autowired
@Lazy
private Environment environmentLazy;


每天用心记录一点点。内容也许不重要,但习惯很重要!

posted on 2020-02-16 20:34  binarylei  阅读(825)  评论(0编辑  收藏  举报

导航