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