Bean注册
如果要注册的bean对象来自于第三方(不是自定义的),是无法用 @Component 及衍生注解声明bean的
方式一:@Bean
1.在启动类中
@springBootApplication
public class springBootRegisterApplication {
@Bean //将方法返回值交给I0C容器管理,成为IOC容器的bean对象
public Resolver resolver(){
return new Resolver();
}
}
2.在配置类中
@Configuration
public class commonconfig {
//对象默认的名字是:方法名
@Bean
public Resolver resolver(){
return new Resolver();
}
}
如果方法的内部需要使用到IOC容器中已经存在的bean对象,那么只需要在方法上声明即可,spring会自动的注入
方式二:@import
1.导入配置类
//可以不在启动类及其子包下
//在启动类上加注解@import(xxx.class)
@Configuration
public class commonconfig {
//对象默认的名字是:方法名
@Bean
public Resolver resolver(){
return new Resolver();
}
}
2.导入 ImportSelector 接实现类
//在启动类上加注解@import(xxx.class)
public class CommonImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingclassMetadata){
return new String[]{"com.xxx.config.CommonConfig"};
}
}
为了让程序变得更灵活
创建一个common.imports
//在该文件写上全类名即可,每一行写一个就可以了
com.xxx.config.CommonConfig
ImportSelector 接实现类
//在启动类上加注解@import(xxx.class)
public class CommonImportSelector implements ImportSelector {
@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]);
}
}
后面可以制定组合注解使用@EnableXxxx注解,封装@Import注解