1.Bean扫描
1.1传统Spring
- 标签:<context:component-scan base-package="com. example "/>
- 注解:@ComponentScan(basePackages = "com.example")
1.2SpringBoot
SpringBoot默认扫描启动类所在的包及其子包
2.Bean注册
如果要注册的bean对象来自于第三方(不是自定义的,可能无法修改,则不能为添加注解),是无法用 @Component 及衍生注解声明bean的
解决
-
2.1@Bean
2.1.1下载jar包
2.1.2导入依赖
2.1.3配置类
如果要注册第三方bean,建议在配置类中集中注册
-
2.2@Import
2.2.1导入配置类
2.2.2导入 ImportSelector 接口实现类
package com.aaa.config;import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;public class CommonImportSelector implements ImportSelector {@Overridepublic 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]);}
}
补充知识:
1、组合配置
2、注入配置文件信息的应用
3.注册条件
SpringBoot提供了设置注册生效条件的注解 @Conditional