当前位置: 首页 > article >正文

Spring Boot 与@Bean注解搭配场景

在Spring Boot中,@Bean注解通常与其他注解一起使用,以实现更灵活的Bean管理、依赖注入和配置。以下是一些常见的搭配使用场景:

1. @Bean@Configuration

@Bean注解通常用于配置类(带有@Configuration注解的类)中,用于声明一个Bean。Spring容器会自动调用带有@Bean注解的方法,并将方法的返回值注册为一个Bean。

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyService();
    }
}

2. @Bean@Scope

@Scope注解可以与@Bean一起使用,用于指定Bean的作用域(如singletonprototype等)。

@Bean
@Scope("prototype")
public MyService myService() {
    return new MyService();
}

3. @Bean@Lazy

@Lazy注解可以与@Bean一起使用,表示延迟加载Bean。这意味着Bean只有在被首次使用时才会被初始化。

@Bean
@Lazy
public MyService myService() {
    return new MyService();
}

4. @Bean@Primary

@Primary注解可以与@Bean一起使用,用于指定当存在多个同类型的Bean时,优先选择哪一个Bean。

@Bean
@Primary
public MyService primaryService() {
    return new MyService();
}

5. @Bean@Profile

@Profile注解可以与@Bean一起使用,用于根据环境激活特定的Bean。

@Bean
@Profile("dev")
public MyService devService() {
    return new DevService();
}

6. @Bean@DependsOn

@DependsOn注解可以与@Bean一起使用,用于指定当前Bean的依赖关系,确保某些Bean在当前Bean初始化之前被创建。

@Bean
@DependsOn("anotherBean")
public MyService myService() {
    return new MyService();
}

7. @Bean@Autowired

@Bean声明的Bean可以通过@Autowired注解在其他组件中被自动注入。

@Service
public class MyService {
    @Autowired
    private MyBean myBean;
}

8. @Bean@Qualifier

当存在多个同类型的Bean时,@Qualifier注解可以与@Autowired一起使用,用于指定注入哪一个Bean。

@Autowired
@Qualifier("myService")
private MyService service;


http://www.kler.cn/a/564875.html

相关文章:

  • 网络安全复习资料
  • Go语言学习笔记(三)
  • 目标检测YOLO实战应用案例100讲-面向无人机图像的小目标检测
  • JAVA面试常见题_基础部分_mybatis面试题
  • 【MySQL】(1) 数据库基础
  • 从工程师到系统架构设计师
  • 【NestJS系列】安装官方nestjs CLI 工具
  • 股指期货交割日对股市有哪些影响?
  • 【前端基础】Day 3 CSS-2
  • git merge -s ours ...的使用方法
  • Lua的table类型的增删改查操作
  • RAG 阿里云
  • Git 安装配置
  • gitlab初次登录为什么登不上去
  • Gin从入门到精通 (六)中间件
  • python3GUI--Fun!音乐播放器 By:PyQt5(附下载地址)
  • 学习大模型开发要学什么
  • SpringCloudAlibaba组件的使用
  • 18.6 大语言模型可解释性解密:打开AI黑箱的关键技术
  • java23种设计模式-策略模式