Spring @Bean注解配置及使用方法解析
使用說明
這個注解主要用在方法上,聲明當(dāng)前方法體中包含了最終產(chǎn)生 bean 實例的邏輯,方法的返回值是一個 Bean。這個 bean 會被 Spring 加入到容器中進行管理,默認情況下 bean 的命名就是使用了 bean 注解的方法名。@Bean 一般和 @Component 或者 @Configuration 一起使用。
@Bean 顯式聲明了類與 bean 之間的對應(yīng)關(guān)系,并且允許用戶按照實際需要創(chuàng)建和配置 bean 實例。
該注解相當(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,兩個均可使用
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,三個均可使用
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(); }}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字2. SpringMVC+Jquery實現(xiàn)Ajax功能3. 基于javaweb+jsp實現(xiàn)企業(yè)財務(wù)記賬管理系統(tǒng)4. 博客日志摘要暨RSS技術(shù)5. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案6. WML學(xué)習(xí)之一概述和基本規(guī)則7. Java pom.xml parent引用報錯問題解決方案8. python 集合set中 add與update區(qū)別介紹9. CSS單標(biāo)簽實現(xiàn)復(fù)雜的棋盤布局10. Java try catch finally異常處理組合詳解
