栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring @Bean注解配置及使用方法解析

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring @Bean注解配置及使用方法解析

使用说明

这个注解主要用在方法上,声明当前方法体中包含了最终产生 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();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/134319.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号