使用說明
這個注解主要用在方法上,聲明當前方法體中包含了最終產生 bean 實例的邏輯,方法的返回值是一個 Bean。這個 bean 會被 Spring 加入到容器中進行管理,默認情況下 bean 的命名就是使用了 bean 注解的方法名。@Bean 一般和 @Component 或者 @Configuration 一起使用。
@Bean
顯式聲明了類與 bean 之間的對應關系,並且允許用戶按照實際需要創建和配置 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();
}
}
參考:https://www.hangge.com/blog/cache/detail_2506.html
https://www.jianshu.com/p/2f904bebb9d0