如何配置和使用Spring@Bean注解

小编这次要给大家分享的是如何配置和使用Spring @Bean注解,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

创新互联是工信部颁发资质IDC服务器商,为用户提供优质的四川移动机房托管服务

使用说明

这个注解主要用在方法上,声明当前方法体中包含了最终产生 bean 实例的逻辑,方法的返回值是一个 Bean。这个 bean 会被 Spring 加入到容器中进行管理,默认情况下 bean 的命名就是使用了 bean 注解的方法名。@Bean 一般和 @Component 或者 @Configuration 一起使用。

@Bean 显式声明了类与 bean 之间的对应关系,并且允许用户按照实际需要创建和配置 bean 实例。

该注解相当于:

普通组件

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();
  }
}

看完这篇关于如何配置和使用Spring @Bean注解的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。


网页名称:如何配置和使用Spring@Bean注解
本文网址:http://bzwzjz.com/article/piesgs.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 成都网站设计 企业手机网站建设 成都网站建设 高端网站设计推广 网站设计 成都网站建设公司 成都网站设计 响应式网站建设 成都网站制作 app网站建设 成都网站建设 成都网站建设 营销网站建设 企业网站制作 四川成都网站建设 营销网站建设 移动网站建设 成都网站制作 网站建设 成都网站建设 成都品牌网站设计 定制级高端网站建设