网站首页 > 教程分享 正文
环境:springboot2.3.9.RELEASE
三种方法说明
- 直接导入普通数组的方式
- 导入ImportSelector类方式
- 导入ImportBeanDefinitionRegistrar方式
被导入的类加入到Spring IOC容器中。
直接导入普通数组的方式
public class A {
@Bean
public B b() {
return new B() ;
}
}
@Import({A.class})
@Configuration
public class ImportConfig {
}
这样A,B都被Spring IOC容器管理了。这里可以导入多个类。
注意:在Spring4.2之前的版本中被导入的类必须是配置类也就是类上有@Configuration注解,4.2后的版本随意一个普通类也可以。
测试:
@Resource
private A a ;
@Resource
private B b ;
@Test
public void testImport() {
System.out.println("a = " + a) ;
System.out.println("b = " + b) ;
}
导入ImportSelector类方式
通过实现ImportSelector接口
public class E {
@Bean
public G g() {
return new G() ;
}
}
public class F {
}
public class G {
}
@Import({C.class, A.class})
@Configuration
public class ImportConfig {
}
public class C implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[] {"com.pack.import_annotation.E", "com.pack.import_annotation.F"};
}
}
这里的返回值中必须是完整的包名+类名
注意:这里可以返回空的String数组(length = 0),但是不能返回null。实现ImportSelector该接口的这个本身是不会被注册为Bean的。
测试:
@Resource
private E e ;
@Resource
private F f ;
@Resource
private G g ;
@Test
public void testImport() {
System.out.println("e = " + e) ;
System.out.println("f = " + f) ;
System.out.println("g = " + g) ;
}
导入ImportBeanDefinitionRegistrar方式
public class H implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
GenericBeanDefinition beanDefinition = new GenericBeanDefinition() ;
beanDefinition.setBeanClass(X.class) ;
beanDefinition.getPropertyValues().addPropertyValue("name", "张三") ;
registry.registerBeanDefinition("x", beanDefinition) ;
}
}
public class X {
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Import({C.class, A.class, H.class})
@Configuration
public class ImportConfig {
}
测试:
注意:实现ImportBeanDefinitionRegistrar该接口本身这个类是不会被注册为Bean的。
完毕!!!
给个关注+转发呗谢谢
SpringBoot2 整合 OAuth2 资源认证(保护)
公众:Springboot实战案例锦集
猜你喜欢
- 2024-09-09 彻底告别python第三方包import问题!只需要7行代码(码住)
- 2024-09-09 python每日一练之如何copy(python copy)
- 2024-09-09 你知道import Vue from 'vue' 吗?
- 2024-09-09 spring中的@import/@ImportResource注解
- 2024-09-09 Spring中@Import注解详解(spring import注解原理)
- 2024-09-09 python首行代码import *,from * import * 解析
- 2024-09-09 Import注解的理解(java @import注解)
- 2024-09-09 link与@import的区别和分别对应的例子
- 2024-09-09 第五章 import导入第三方库或者模块
- 2024-09-09 ES6模块化一缕(export、import)(es6模块化引入)
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- css导航条 (66)
- sqlinsert (63)
- js提交表单 (60)
- param (62)
- parentelement (65)
- jquery分享 (62)
- check约束 (64)
- curl_init (68)
- sql if语句 (69)
- import (66)
- chmod文件夹 (71)
- clearinterval (71)
- pythonrange (62)
- 数组长度 (61)
- javafx (59)
- 全局消息钩子 (64)
- sort排序 (62)
- jdbc (69)
- php网页源码 (59)
- assert h (69)
- httpclientjar (60)
- postgresql conf (59)
- winform开发 (59)
- mysql数字类型 (71)
- drawimage (61)
本文暂时没有评论,来添加一个吧(●'◡'●)