12. Bean 获取,作用域,管理

  1. Bean 获取,作用域,管理

在IOC容器中,每一个Bean都有一个属于自己的名字,可以通过注解的value属性指定bean的名字。如
果没有指定,默认为类名首字母小写。

1.问题:使用前面学习的四个注解声明的bean,一定会生效吗?
答案:不一定。(原因:bean想要生效,还需要被组件扫描)

@SpringBootApplication 中默认扫描的范围是SpringBoot启动类所在包及其子包

使用四大注解声明的bean,要想生效,还需要被组件扫描注解@ComponentScan({"dao","com.alex"})扫描指定包路径的类
	
2.面试题 : @Autowird 与 @Resource的区别
@Autowired 是spring框架提供的注解,而@Resource是JDK提供的注解
@Autowired 默认是按照类型注入,而@Resource是按照名称注入

当存在多个相同类型的Bean注入时,加上@Primary注解,来确定默认的实现
public class EmpController {
   // @Autowired
    @Resource(name="empServiceA")   //@Resource(name="empServiceB")
    private EmpService empService;

默认情况下,spring项目启动时,会把bean都创建好放在IOC容器中,如何想主动获取这些bean,可以通过如下方式获取:getBean()

@Autowired
private ApplicationContext applicationContext;//IOC容器对象

类名  lei=(类名)applicationContext.getBean("类名");

@Singleton bean默认是单列的,在容器启动时被创建,可以使用@Lazy注解延迟初始化
@Scope("prototype")

---------------------------------声明第三方bean,获取bean-------------------------------

在类上添加@Component 注解来注入IOC容器,但是对应引入的第三方包不能修改怎么注入呢?用@Bean

@SpringBootApplication
public class SpringbootAopQuickstartApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootAopQuickstartApplication.class, args);
    }

//声明第三方bean 
    @Bean //将方法返回值交给IOC容器管理,成为IOC容器的bean对象(第3方包)
    public SAXReader saxReader(){
        return new Saxreader();
    }
}

---------------------------------声明第三方bean,获取bean-------------------------------

@Configuration
public class CommonConfig {
 
//声明第三方bean 
    @Bean //将方法返回值交给IOC容器管理,成为IOC容器的bean对象(第3方包)
    public SAXReader saxReader(){    //saxReader 方法名是bean对象
        return new Saxreader();
    }
}



    @Test
    public void testGetBean(){
        Object saxReader=applicationContext.getBean("reader");
        System.out.println(saxReader);
    }

注解注入IOC容器:

@Component
@Controller
@Service
@Repository
posted @ 2023-06-24 23:26  大树2  阅读(11)  评论(0编辑  收藏  举报