Springboot3.4.x中的@Bean使用案例
作者:考虑考虑
Spring Boot 3.4.x中@Bean新增defaultCandidate=false属性,用于在存在相同类型Bean时忽略非默认候选者,确保仅实例化一个Bean,下面就来介绍一下如何使用
前言
Springboot3.4.x
版本中的@Bean新增一个字段defaultCandidate = false
,当类型匹配时,基于 Bean 的条件现在将忽略任何不是默认候选者的 Bean
defaultCandidate字段使用
1、 定义一个接口
public interface UserService { void add(); }
2、定义一个接口
@Slf4j public class PersonServiceImpl implements UserService { @Override public void add() { log.info("测试1============="); } }
3、定义一个接口
@Slf4j public class UserServiceImpl implements UserService { @Override public void add() { log.info("测试============="); } }
4、使用@Bean
@Configuration public class UserServiceConfig { @Bean public UserService add() { return new UserServiceImpl(); } @Bean(defaultCandidate = false) public UserService add1() { return new PersonServiceImpl(); } }
5、定义一个接口
@Slf4j @RestController public class IndexController { @Autowired private List<UserService> userServiceList; @GetMapping("/hello") public String hello() { log.info("数据为:{{}}", userServiceList); return "success"; } }
访问地址
http://ip:端口/hello
输出结果为
只实例化一个
总结
Springboot3.4.x中的@Bean中的defaultCandidate = false
,如果存在相同类型的 bean,它就会被忽略
到此这篇关于Springboot3.4.x中的@Bean使用案例的文章就介绍到这了,更多相关Springboot3.4.x @Bean使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!