温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-30 11:23:26 来源:亿速云 阅读:220 作者:小猪 栏目:编程语言

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

使用说明

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI