Spring @Bean注解配置及使用方法解析
使用說(shuō)明
這個(gè)注解主要用在方法上,聲明當(dāng)前方法體中包含了最終產(chǎn)生 bean 實(shí)例的邏輯,方法的返回值是一個(gè) Bean。這個(gè) bean 會(huì)被 Spring 加入到容器中進(jìn)行管理,默認(rèn)情況下 bean 的命名就是使用了 bean 注解的方法名。@Bean 一般和 @Component 或者 @Configuration 一起使用。
@Bean 顯式聲明了類與 bean 之間的對(duì)應(yīng)關(guān)系,并且允許用戶按照實(shí)際需要?jiǎng)?chuàng)建和配置 bean 實(shí)例。
該注解相當(dāng)于:
<bean />
普通組件
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration; @Configurationpublic class MyConfigration { @Bean public User user() { return new User; }}
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class UserController { @Autowired User user; @GetMapping('/test') public User test() { return user.test(); }}
命名組件
bean 的命名為:user,別名為:myUser,兩個(gè)均可使用
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyConfigration { @Bean(name = 'myUser') public User user() { return new User; }}
bean 的命名為:user,別名為:myUser / yourUser,三個(gè)均可使用
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyConfigration { @Bean(name = {'myUser', 'yourUser'}) public User user() { return new User; }}
Bean 初始化和銷毀
public class MyBean { public void init() { System.out.println('MyBean初始化...'); } public void destroy() { System.out.println('MyBean銷毀...'); } public String get() { return 'MyBean使用...'; }}
@Bean(initMethod='init', destroyMethod='destroy')public MyBean myBean() { return new MyBean();}
只能用 @Bean 不能使用 @Component
@Beanpublic OneService getService(status) { case (status) { when 1:return new serviceImpl1(); when 2:return new serviceImpl2(); when 3:return new serviceImpl3(); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 開(kāi)發(fā)效率翻倍的Web API使用技巧2. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. 什么是Python變量作用域5. ASP常用日期格式化函數(shù) FormatDate()6. CSS3中Transition屬性詳解以及示例分享7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. java加載屬性配置properties文件的方法9. Python數(shù)據(jù)相關(guān)系數(shù)矩陣和熱力圖輕松實(shí)現(xiàn)教程10. python 如何在 Matplotlib 中繪制垂直線
