Spring註解之@Import用法

最近在看spring5.1以及mybatis-spring源碼的時候,發現@MapperScan以及很多springboot的@EnableXXX註解,都用到了這個@Import註解。所以打算仔細研究下該註解的作用。

順便把類似的@ImportRescource也在這裏總結一下。

 一、@Import簡介

簡介:在Spring3.0之前,我們的bean可以通過xml配置文件和掃描特定包下的類來將指定的bean注入到Spring容器中。Spring 3.0之後提供了JavaConfig的方式,也就是將Spring容器裏bean的元信息以java代碼的方式進行描述。即通過@Configuration與@Bean這兩個註解配合使用來將原來配置在xml文件裏的Bean通過java代碼的方式進行描述,進而將bean注入到Spring容器中

根據下面的源碼,我們可以簡單的總結,主要有三種用法:

  • 功能類似XML配置的,用來導入配置類。
  • 可以導入帶有@Configuration註解的配置類或實現了ImportSelector或portBeanDefinitionRegistrar。
  • 導入普通的POJO(Spring會將其註冊成Spring Bean,導入POJO需要使用Spring 4.2以上)。
/*
 * Copyright 2002-2016 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
 *
 *      http://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.context.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;

/**
 * Indicates one or more {@link Configuration @Configuration} classes to import.
 *
 * <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
 * Allows for importing {@code @Configuration} classes, {@link ImportSelector} and
 * {@link ImportBeanDefinitionRegistrar} implementations, as well as regular component
 * classes (as of 4.2; analogous to {@link AnnotationConfigApplicationContext#register}).
 *
 * <p>{@code @Bean} definitions declared in imported {@code @Configuration} classes should be
 * accessed by using {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
 * injection. Either the bean itself can be autowired, or the configuration class instance
 * declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly
 * navigation between {@code @Configuration} class methods.
 *
 * <p>May be declared at the class level or as a meta-annotation.
 *
 * <p>If XML or other non-{@code @Configuration} bean definition resources need to be
 * imported, use the {@link ImportResource @ImportResource} annotation instead.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.0
 * @see Configuration
 * @see ImportSelector
 * @see ImportResource
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {

	/**
	 * {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
	 * or regular component classes to import.
	 */
	Class<?>[] value();

}

 

二、@Import用法詳解 

1、ImportSelector

  • 根據AnnotationMetadata(實質上是引入標註了@Import註解的類的註解信息),來判斷是否引入哪些配置類,通過字符串數組的方式返回配置類的全限定名。

2、DeferredImportSelector

  • ImportSelector的子接口,區別是,他會在所有的@Configuration類加載完成之後再加載返回的配置類。ImportSelector會在當前Configuration類加載之前去加載返回的配置類。
  • 可以使用@Order註解或者Ordered接口來指定DeferredImportSelector的加載順序。
  • 並且提供了新的方法getImportGroup()用來跨DeferredImportSelector實現自定義Configuration的加載順序。

3、ImportBeanDefinitionRegistrar

  • 根據AnnotationMetadata(實質上是引入標註了@Import註解的類的註解信息), 來註冊BeanDenfinition,通過BeanDefinitionRegistry實例的register可以註冊BeanDefinition。

三、@Import代碼測試 

package com.evan.config;

import com.evan.service.JustinService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({MyImportSelector.class,MyImportBeanDefinitionRegistrar.class,OtherConfig.class, JustinService.class})
public class MyConfig {

}
package com.evan.config;

import com.evan.service.TomService;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
//使用ImportBeanDefinitionRegistrar的方式,直接導入BeanDefinition
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("TomService", new RootBeanDefinition(TomService.class));
    }
}
package com.evan.config;

import com.evan.service.EvanService;
import com.evan.service.PersonService;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
//使用ImportSelector導入,相當於@Bean
public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //返回String數組。
        return new String[]{EvanService.class.getName(), PersonService.class.getName()};
    }
}
package com.evan.config;

import com.evan.service.JayService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//直接導入配置類
@Configuration
public class OtherConfig {
    @Bean
    public JayService jay(){
        return new JayService();
    }
}

 

package com.evan.service;

public class EvanService {
}

 

package com.evan.service;

public class JayService {
}

 

package com.evan.service;

public class JustinService {
}

 

package com.evan.service;

public class PersonService {
}

 

package com.evan.service;

public class TomService {
}

主測試類:

package com.evan.test;

import com.evan.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
        ac.register(MyConfig.class);
        ac.refresh();
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
    }
}

運行結果: 

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
com.evan.service.EvanService
com.evan.service.PersonService
com.evan.config.OtherConfig
jay
com.evan.service.JustinService
TomService

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章