bean的扫描
默认只能扫描启动类所在的包及其自包,其他的扫描不到,如果需要扫描需要手动添加@ComponentScan
bean的注册 建议在配置类中集中注册(不建议直接在启动类中注册)
注解
方法一:@Bean
@Bean注解来把第三方对象注入到ioc容器,使用@Configuration注解来标识注册类,在注册类中使用@Bean注解来让方法的返回值注入到ioc容器中。假设有第三方对象 Country 和 Province
@Configuration
public class Config{
@Bean
public Country country(){
return new Countery();
}
}
//如果在bean方法注册的内部需要使用的到已经存在的bean对象,只需要申明即可,spring会自动注入,
//以上已经完成了Country的注入,现在在注入Province的时候需要用到Country只需要申明即可。
@Configuration
public class Config{
@Bean
public Country country(){
return new Countery();
}
//在这里注册Country,申明Country country
@Bean
public Province province(Country country){
//在这里用到已经注册好的Country
System.out.println(country);
return new Province();
}
}
二、@Import方法 @Import(xxx.class)
一般用于导入配置类(就是上面方法一说的类),或者导入ImportSelector接口实现类
1.编写接口实现类
public class CommonConfigSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//传入配置类的全类名,可以是多个组成数组
return new String[]{"com.springboot.demo.config.CommonConfig"};
}
}
2.启动类中使用@Import导入接口实现类
@SpringBootApplication
@Import(CommonConfigSelector.class)//此时导入即可完成注入
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
}
}
//自动完成扫描
获取注册的bean
使用启动类的返回对象 ApplicationContext 中的getBean方法传入第三方对象的字节码,或者传入对象的名字,对象名字默认是bean的方法名 context.getBean("方法名"),可以通过@bean("对象的名字")给bean取新的名字
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
//在这里获取context
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
//调用context.getBean方法。传入字节码或者bean对象的名字
Country country = context.getBean(Country.class);
}
}