Springboot3.4.x中的@Bean使用

300 阅读1分钟

前言

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

输出结果为

image.png 只实例化一个

总结

Springboot3.4.x中的@Bean中的defaultCandidate = false,如果存在相同类型的 bean,它就会被忽略