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. 组合注解

启动类直接使用组合注解

相关推荐
CQU_JIAKE2 分钟前
4.17[Q]
java·linux·服务器
张赐荣13 分钟前
跨平台无障碍版随机数生成器
windows
胖少年25 分钟前
从零开始:在 Windows 上用 llama.cpp 跑本地大模型
windows·llama
小狄同学呀32 分钟前
同样的global,不同的audioLibPath——记一次诡异的内存错位
c++·windows
亦暖筑序37 分钟前
Spring AI Alibaba 报错合集:我踩过的那些坑
java·后端
宋小黑1 小时前
推荐一款好用的 Windows C盘垃圾清理工具,告别C盘爆满!
windows
indexsunny1 小时前
互联网大厂Java面试实战:核心技术与微服务架构在电商场景中的应用
java·spring boot·redis·kafka·maven·spring security·microservices
摇滚侠1 小时前
Java 多线程基础 Java Multithreading Basics
java