打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
spring @Bean注解的使用

@Bean 的用法

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

定义bean

下面是@Configuration里的一个例子

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

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

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

bean的依赖

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

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

接受生命周期的回调

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

public class Foo {    public void init() {        // initialization logic    }}public class Bar {    public void cleanup() {        // destruction logic    }}@Configurationpublic 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注解

你能够使用@Scope注解来指定使用@Bean定义的bean

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

@Scope and scoped-proxy

spring提供了scope的代理,可以设置@Scope的属性proxyMode来指定,默认是ScopedProxyMode.NO, 你可以指定为默认是ScopedProxyMode.INTERFACES或者默认是ScopedProxyMode.TARGET_CLASS。
以下是一个demo,好像用到了(没看懂这块)

// an HTTP Session-scoped bean exposed as a proxy@Bean@SessionScopepublic UserPreferences userPreferences() {    return new UserPreferences();}@Beanpublic Service userService() {    UserService service = new SimpleUserService();    // a reference to the proxied userPreferences bean    service.setUserPreferences(userPreferences());    return service;}

自定义bean的命名

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

@Configurationpublic class AppConfig {    @Bean(name = "myFoo")    public Foo foo() {        return new Foo();    }}

bean的别名

bean的命名支持别名,使用方法如下

@Configurationpublic class AppConfig {    @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })    public DataSource dataSource() {        // instantiate, configure and return DataSource bean...    }}

bean的描述

有时候提供bean的详细信息也是很有用的,bean的描述可以使用 @Description来提供

@Configurationpublic class AppConfig {    @Bean    @Description("Provides a basic example of a bean")    public Foo foo() {        return new Foo();    }}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
[Java][web]利用Spring随时随地获得Request和Session | IT瘾
浅谈 Spring Boot 中的 @Conditional 注解
Spring-IOC进阶注解
使用Java方式配置Spring
托管 Bean 页面传值的使用方法和技巧
Spring多数据源的配置和使用
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服