1. 程式人生 > >spring @Bean註解的使用

spring @Bean註解的使用

@Bean 的用法

@Bean是一個方法級別上的註解,主要用在@Configuration註解的類裡,也可以用在@Component註解的類裡。新增的bean的id為方法名

定義bean

下面是@Configuration裡的一個例子

@Configuration
public class AppConfig {

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

}

這個配置就等同於之前在xml裡的配置

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

bean的依賴

@bean 也可以依賴其他任意數量的bean,如果TransferService 依賴 AccountRepository,我們可以通過方法引數實現這個依賴

@Configuration
public 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
    }
}

@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註解

你能夠使用@Scope註解來指定使用@Bean定義的bean

@Configuration
public 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
@SessionScope
public UserPreferences userPreferences() {
    return new UserPreferences();
}

@Bean
public Service userService() {
    UserService service = new SimpleUserService();
    // a reference to the proxied userPreferences bean
    service.setUserPreferences(userPreferences());
    return service;
}

自定義bean的命名

預設情況下bean的名稱和方法名稱相同,你也可以使用name屬性來指定

@Configuration
public class AppConfig {

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

}

bean的別名

bean的命名支援別名,使用方法如下

@Configuration
public class AppConfig {

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

}

bean的描述

有時候提供bean的詳細資訊也是很有用的,bean的描述可以使用 @Description來提供

@Configuration
public class AppConfig {

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

}