一, 第一个待注入类

public class CacheService {
}

public class LoggerService {
}

  

方法一, 实现接口ImportSelectort

public class CacheImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{CacheService.class.getName()};
    }
}

 

方法二, 实现接口ImportBeanDefinitionRegistrar,

public class LoggerServiceSelector implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(LoggerService.class);
        String strBeanname = StringUtils.uncapitalize(LoggerService.class.getName());
        beanDefinitionRegistry.registerBeanDefinition(strBeanname, rootBeanDefinition);
    }
}

 

 

自定义Enable注解, 将CacheService, LoggerService加载到Spring-boot项目中

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
@Import({CacheImportSelector.class, LoggerServiceSelector.class})
public @interface EnableCacheService {
}



//启动Spring-boot

@EnableCacheService
@SpringBootApplication
public class SpringBootDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(SpringBootDemoApplication.class, args);
        CacheService cacheService = context.getBean(CacheService.class);
        System.out.println(cacheService.toString());
        LoggerService loggerService = context.getBean(LoggerService.class);
        System.out.println(loggerService);
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-10-18
  • 2021-07-07
  • 2021-11-18
  • 2021-09-30
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-25
  • 2021-10-21
  • 2021-11-17
  • 2021-05-21
相关资源
相似解决方案