首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >spring @Import

spring @Import

作者头像
平凡的学生族
发布2019-05-25 09:26:31
发布2019-05-25 09:26:31
1.5K00
代码可运行
举报
文章被收录于专栏:后端技术后端技术
运行总次数:0
代码可运行

1. 导入Configuration

Spring框架中的@Import注解向我们展示了@Import的两种用法:

  1. 通过在@Configuration类上使用@Import导入其它的@Configuration,来将多个配置导入到一个主配置中,避免将所有配置写在一个配置中。 @Configuration @Import({JavaConfigA.class,JavaConfigB.class}) public class ParentConfig { //Any other bean definitions }

此处,ParentConfig是主配置,JavaConfigA和JavaConfigB都是@Configuration类,各自用@Bean方法定义了自己的Bean。

2. 导入普通java类

在4.2以后,也可以导入普通的java类,并将其声明成一个bean

代码语言:javascript
代码运行次数:0
运行
复制
// 一个普通java类
public class DemoService {  
    public void doSomething(){  
        System.out.println("ok");  
    }  
}  
代码语言:javascript
代码运行次数:0
运行
复制
import org.springframework.context.annotation.Configuration;  
import org.springframework.context.annotation.Import;  
  
// Configuration将导入DemoService
@Configuration  
@Import(DemoService.class) //在spring 4.2之前是不不支持的  
public class DemoConfig {  
  
}  
代码语言:javascript
代码运行次数:0
运行
复制
import org.springframework.context.annotation.AnnotationConfigApplicationContext;  
  
public class Main {  
    public static void main(String[] args) {  
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com..example");  
        DemoService ds = context.getBean(DemoService.class);  
        ds.doSomething();  
    }  
  
}  

输出结果:ok

3. 导入ImportSelector的实现类

Spring中@Import注解的作用和使用

4. 导入ImportBeanDefinitionRegistrar的实现类

Spring中@Import注解的作用和使用

@Import用于@interface

阅读Spring - @Configuration selection by using ImportSelector中的Using Annotation based ImportSelector部分

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.05.18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 导入Configuration
  • 2. 导入普通java类
  • 3. 导入ImportSelector的实现类
  • 4. 导入ImportBeanDefinitionRegistrar的实现类
  • @Import用于@interface
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档