在Spring Boot中,@Bean注解通常与其他注解一起使用,以实现更灵活的Bean管理、依赖注入和配置。以下是一些常见的搭配使用场景:
1. @Bean与@Configuration
@Bean注解通常用于配置类(带有@Configuration注解的类)中,用于声明一个Bean。Spring容器会自动调用带有@Bean注解的方法,并将方法的返回值注册为一个Bean。
@Configuration
public class AppConfig {@Beanpublic MyService myService() {return new MyService();}
}
2. @Bean与@Scope
@Scope注解可以与@Bean一起使用,用于指定Bean的作用域(如singleton、prototype等)。
@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 {@Autowiredprivate MyBean myBean;
}
8. @Bean与@Qualifier
当存在多个同类型的Bean时,@Qualifier注解可以与@Autowired一起使用,用于指定注入哪一个Bean。
@Autowired
@Qualifier("myService")
private MyService service;
