@Bean

1. @Bean

介绍 :

是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里,添加的bean的id为方法名

定义Bean

下面是一个例子

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

这个配置就等同于之前在xml里面的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

<bean>必须包含id和class,id是用于之后的搜索查询,而class是指定类的路径或者类名

bean的依赖

@bean也可以依赖其他数量的bean,如果TransferService依赖AccountRespository,我们可以通过方法参数来实现这个依赖

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService(AccountRepository accountRepository) {
        return new TransferServiceImpl(accountRepository);
    }
}

接受生命周期的回调

任何使用@bean定义的bean,也可以执行生命周期的回调函数,类似于@PostConstruct 和 @ PreDestory的方法,用法如下

public class Foo {
    public void init() {
        // initialization logic
    }
}
public class Bar {
    public void cleanup() {
        // destruction logic
    }
}
=============================
@Configuration
public class AppConfig {
    @Bean(initMethod = "init")//初始化的时候执行的方法
    public Foo foo() {
        return new Foo();
    }
    @Bean(destroyMethod = "cleanup")//销毁时候执行的方法
    public Bar bar() {
        return new Bar();
    }
}

默认使用javaConfig配置的bean,如果存在close或者shutdown方法,则在bean销毁时会自动执行该方法,如果你不想执行该方法,则添加@Bean(destroyMethod="")来防止出发销毁方法

bean的作用域

使用scope注解
能使用@Scope注解俩指定使用@Bean定义的bean.默认是单例,可以设置为多例单例就是不管你使用多少次在springIOC容器中只会存在一个实例,多利就是使用一次创建一个实例(new 一个对象)

@Configuration
public class MyConfiguration {
    @Bean
    @Scope("prototype")
    public Encryptor encryptor() {
        // ...
    }
}

自定义bean的命名

默认情况下bean的名称和方法名相同,可以使用name属性来指定,例如

@Configuration
public class AppConfig {
    @Bean(name = "myFoo")
    public Foo foo() {
        return new Foo();
    }
}
posted @ 2021-09-30 11:08  1_f  阅读(37)  评论(0)    收藏  举报