网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 生活百科 知识问答 更多知识

Spring中使用ImportSelector注解进行组件注册

时间:2026-02-14 17:28:52

1、ImportSelector代表返回需要导入的组件全类名的数组:

2、ImportSelector接口中方法String[] selectImports(AnnotationMetadata importingClassMetadata)

返回值就是要导入到容器中的组件全类名

 importingClassMetadata参数标识当前标注@Import注解的类的所有注解信息

Spring中使用ImportSelector注解进行组件注册

3、自定义一个ImportSelector接口的实现类:MyImportSelector。

package com.gwolf.config;

import org.springframework.context.annotation.ImportSelector;

import org.springframework.core.type.AnnotationMetadata;

public class MyImportSelector implements ImportSelector {

        /**         * 返回值就是要导入到容器中的组件全类名       

                *importingClassMetadata参数标识当前标注@Import注解的类的                    所有注解信息       

        */      

 @Override       

public String[] selectImports(AnnotationMetadata importingClassMetadata) {               

         return new String[] {"com.gwolf.vo.Red"};     

   }

}

Spring中使用ImportSelector注解进行组件注册

4、在组件注册配置类上加上上述的自定义实现类:

package com.gwolf.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Conditional;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Import;

import com.gwolf.vo.Color;

import com.gwolf.vo.Person;

@Configuration

@Conditional(value= {WindowsCondition.class})

@ComponentScanImport(value= {Color.class,MyImportSelector.class})

public class ComponentConfig {     

 }

Spring中使用ImportSelector注解进行组件注册

5、编写junit测试类,查看我们自定义的类中的组件是不是加入到容器中了。

package com.gwolf.test;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.gwolf.config.ComponentConfig;

public class ComponentTest {

          ApplicationContext applicationContext =  new AnnotationConfigApplicationContext(ComponentConfig.class);  

     

    @Test       

   public void testImport() {              

       String[] beanNames = applicationContext.getBeanDefinitionNames();                               

   for(String bean : beanNames) {                  

      System.out.println(bean);              

     }      

  }

}

Spring中使用ImportSelector注解进行组件注册

6、查看程序的运行结果:Red类已经加入到spring容器中了。

Spring中使用ImportSelector注解进行组件注册

© 2026 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com