spring的bean注册

  1. bean注册
  1. 第三方jar包的类想添加到ioc中,加不了@Component该怎么办呢。
    1. 可以使用@Bean和@Import
  2. 引入jar包,可以使用maven安装到本地仓库。
  1. 修改bean的名字:@Bean("aaa")
  2. 使用ioc的已经存在的bean对象,如Country:public Province province(Country country)
  3. 手动扫描类:@Import(CommonConfig.class)
  4. 手动扫描类,优雅地加入多个: @Import(CommonImportSelector)
java 复制代码
public class CommonImportSelector implements ImportSelector {
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.itheima.config.CommonConfig"};
    }
}
  1. 读配置文件,类名和上面一致。方法不同。

    java 复制代码
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //读取配置文件的内容    List<String> imports = new ArrayList<>();
        InputStream is = CommonImportSelector.class.getClassLoader().getResourceAsStream("common.imports");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        try {
            while((line = br.readLine())!=null){
                imports.add(line);
            }
    
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return imports.toArray(new String[0]);
    }
  2. 组合注解

启动类直接使用组合注解

相关推荐
折哥的程序人生 · 物流技术专研15 小时前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
researcher-Jiang15 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
夜雪一千16 小时前
Python enumerate() 函数完整详解:遍历同时获取索引,告别手动计数
服务器·windows·python
西门吹-禅17 小时前
java springboot N+1问题
java·开发语言·spring boot
DLYSB_17 小时前
生命通道:如何用 HIS 医疗系统直连网络声光终端,打造“零延误”的危急值响应网关?
java·网络·数据库·报警灯
weixin_BYSJ198718 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
AI小码18 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
Hui Baby18 小时前
Spring Security
java·后端·spring
IT笔记19 小时前
【Rust】Rust Match 模式匹配详解
java·开发语言·rust
我才是银古20 小时前
构建 Java GIS 工具库:从碎片化 API 到统一抽象的设计实践
java·gis·geotools·gdal·esri