- bean注冊
- 第三方jar包的類想添加到ioc中,加不了@Component該怎么辦呢。
- 可以使用@Bean和@Import
- 引入jar包,可以使用maven安裝到本地倉庫。
- 修改bean的名字:@Bean("aaa")
- 使用ioc的已經存在的bean對象,如Country:public Province province(Country country)
- 手動掃描類:@Import(CommonConfig.class)
- 手動掃描類,優雅地加入多個: @Import(CommonImportSelector)
-
public class CommonImportSelector implements ImportSelector {public String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{"com.itheima.config.CommonConfig"};} }
- 讀配置文件,類名和上面一致。方法不同。
@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]); }
- 組合注解
啟動類直接使用組合注解