SpringBoot - @Configuration,@Bean,@Scope 组件注入容器

@Configuration

作用:声明一个类为配置类,替代之前使用的xml文件

范围:类上

参数:proxyBeanMethods:boolean(default=true)

 

基本使用:注册一个类到IOC容器中

@Configuration
public class MyConfiguration {
    @Bean
    public Object object(){
        return new Object();
    }
}

 

proxyBeanMethods 参数说明:

proxyBeanMethods=true=Full模式

proxyBeanMethods=false=Lite模式

Full模式保证了组件是单例的,每次实例化一个组件,都要去IOC容器里面查看组件是否存在

Lite模式 不能声明@Bean之间的依赖,实例化时每次都是重新创建对象

配置类组件之间无依赖关系时使用Lite模式,这样做可以加快容器启动速度,减少判断

配置类组件之间有依赖关系时使用Full模式,这样做可以保证当方法被调用时,得到之前单实例的组件


@Bean

作用:把类注入到容器当中

范围:方法上

参数:name{} 声明组件的名称,initMethod/destroyMethod声明组件实例化之前于销毁之前会执行的方法

 

@Scope

作用:配合@Bean使用 设置类是单例还是多例

范围:类上,方法上

参数:value:singleton 单例 默认值,prototype 多例

 

基本使用:把类注入到容器,声明单例与多例

@Configuration
public class MyConfiguration {

    @Bean(name="testObject",initMethod = "init",destroyMethod = "destory")
    @Scope(value="prototype")
    public Object object1(){
        return new Object();
    }
    
    //默认名称为方法名称 object2,scope默认为单例singleton
    @Bean
    @Scope
    public Object object2(){
        return new Object();
    }
}

 

posted on 2022-12-20 15:06  Mikasa-Ackerman  阅读(111)  评论(0编辑  收藏  举报

导航