Creating only one bean instance from interface

Viewed 293

I have a interface named IpAssginer and two classes that implement IpAssginer named CloudIpAssginer & DHCPClientService.

I'm trying to set a default IpAssginer to use based on some information on the system startup.

The following code does it successfully but two instances of the selected bean are being created:

@Configuration
public class BeanConfiguration {
    
    @Autowired
    private ShellUtilsService shellUtilsService;
    @Autowired
    private IpAssginer cloudIpAssginer;
    @Autowired
    private IpAssginer dhcpClientService;
    
    @Bean(name = "ipAssginer")
    public IpAssginer ipAssginer() {
    HwType hwType = shellUtilsService.getHwType();
    IpAssginer ipAssginer = hwType.isInCloud() ? cloudIpAssginer : dhcpClientService;
    Log.Management.info("{} IpAssginer created with type: {}", this.getClass().getSimpleName(),
        ipAssginer.getIPAssginerType());
    return ipAssginer;
    }

}

any ideas how I can do the same but create only one instance from the selected bean?

2 Answers

You can use @Bean annotation to create spring bean as well, remove the stereotype annotations from CloudIpAssginer and DhcpClientService class, and then use @Bean annotation in @Configuration class

@Configuration
public class BeanConfiguration {

    @Autowired
    private ShellUtilsService shellUtilsService;


    @Bean(name = "ipAssginer")
    public IpAssginer ipAssginer() {

        HwType hwType = shellUtilsService.getHwType();
        IpAssginer ipAssginer = hwType.isInCloud() ? new CloudIpAssginer() : new DhcpClientService();
        Log.Management.info("{} IpAssginer created with type: {}", this.getClass().getSimpleName(),
        ipAssginer.getIPAssginerType());
        return ipAssginer;

    }

}

A solution that worked for me:

I excluded the IpAssigner from the context and it worked with the following code:

@Configuration
public class BeanConfiguration {

    @Autowired
    private ShellUtilsService shellUtilsService;
    
    @Bean(name = "ipAssginer")
    @DependsOn("cloudApiService")
    public IpAssigner ipAssginer() {
    HwType hwType = shellUtilsService.getHwType();
    IpAssigner ipAssginer = hwType != null && hwType.isInCloud() ? new CloudIpAssginer()
        : new DHCPClientService();
    return ipAssginer;
    }

    
}
Related