方法一:使用@Bean注解(不建议)
首先启动类SpringbootRegisterApplication扫描的是本包以及子包的内容,我们只需在启动类中声明一个方法即可。
@SpringBootApplication
public class SpringbootRegisterApplication {
public static void main(String[] args) {
ApplicationContext context=SpringApplication.run(SpringbootRegisterApplication.class, args);
System.out.println(context.getBean("country")); //判断是否注入成功
}
@Bean //也可以Bean("name") name为Bean对象名
public Reolver resolver(){ //默认Bean对象就是方法名
return new Resolver();
}
}
方法二:在配置类中集中注册
在启动类所在包中创建配置类
@Configuration
public class CommonConfig {
@Bean
public Country country()
{
return new Country();
}
@Bean
public Province province(Country country)
{
return new Province();
}
}
方法三:使用@Import注解
在启动类上导入需要配置的类对象即可,一般为配置类和ImportSelector的接口实现类。
一、导入配置类
@Import({CommonConfig.class})
@SpringBootApplication
public class SpringbootRegisterApplication {
public static void main(String[] args) {
ApplicationContext context=SpringApplication.run(SpringbootRegisterApplication.class, args);
System.out.println(context.getBean("country"));
System.out.println(context.getBean("province"));
}
}
二、导入Selector接口实现类(适用于导入多个类)
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]); //可以简洁的导入多个类
}
}
在启动类上添加@Import(CommonImportSelector.class)即可,