@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
【Bean的Scope】
Scope 描述的是Spring 容器如何新建Bean 的實例的。Spring 的Scope 有以下幾種,通過@Scope 注解來實現。
1. Singleton :一個Spring 容器中只有一個Bean 的實例,此為Spring 的默認配置,全容器共享一個實例。
2. Prototype :每次調用新建一個Bean 的實例。
3. Request: Web 項目中,給每一個http request 新建一個Bean 實例。
4. Session: Web 項目中,給每一個http session 新建一個Bean 實例。
5. Global Session :這個只在portal 應用中有用,給每一個global http session 新建一個Bean
實例。
6. 在Spring Batch 中還有一個Scope 是使用@StepScope
如果希望在啟動的時候加載以后不在加載,使用單例模式,就是
@Scope("Singleton") 或者 @Scope,因為默認情況下就是 單例的;
@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(); } }
參考:spring @Bean注解的使用
參考:04-SpringBoot——Spring常用配置-Bean的Scope