Spring @Bean注解配置及使用方法解析
使用說明
這個注解主要用在方法上,聲明當前方法體中包含了最終產(chǎn)生 bean 實例的邏輯,方法的返回值是一個 Bean。這個 bean 會被 Spring 加入到容器中進行管理,默認情況下 bean 的命名就是使用了 bean 注解的方法名。@Bean 一般和 @Component 或者 @Configuration 一起使用。
@Bean 顯式聲明了類與 bean 之間的對應關系,并且允許用戶按照實際需要創(chuàng)建和配置 bean 實例。
該注解相當于:
<bean id="useService" class="com.test.service.UserServiceImpl"/>
普通組件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public 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;
@RestController
public 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;
@Configuration
public 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;
@Configuration
public 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
@Bean
public OneService getService(status) {
case (status) {
when 1:
return new serviceImpl1();
when 2:
return new serviceImpl2();
when 3:
return new serviceImpl3();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
java發(fā)送http請求并獲取狀態(tài)碼的簡單實例
下面小編就為大家?guī)硪黄猨ava發(fā)送http請求并獲取狀態(tài)碼的簡單實例。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05
在SpringBoot中使用YourKit進行性能調(diào)優(yōu)的教程詳解
在應用程序的開發(fā)過程中,性能調(diào)優(yōu)是一個重要的環(huán)節(jié),在SpringBoot應用程序中,我們可以使用YourKit來進行性能調(diào)優(yōu),YourKit是一款非常強大的Java性能調(diào)優(yōu)工具,在本文中,我們將介紹如何在 SpringBoot應用程序中使用YourKit進行性能調(diào)優(yōu)2023-06-06
Feign遠程調(diào)用Multipartfile參數(shù)處理
這篇文章主要介紹了Feign遠程調(diào)用Multipartfile參數(shù)處理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot+Hibernate實現(xiàn)自定義數(shù)據(jù)驗證及異常處理
這篇文章主要為大家介紹了SpringBoot如何整合Hibernate自定義數(shù)據(jù)驗證及多種方式異常處理,文中的示例代碼講解詳細,感興趣的可以了解一下2022-04-04

