Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从接口仅创建一个bean实例_Java_Spring_Spring Boot - Fatal编程技术网

Java 从接口仅创建一个bean实例

Java 从接口仅创建一个bean实例,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个名为IpAssginer的接口和两个实现IpAssginer的类,分别名为CloudIpAssginer和DHCPClientService 我正在尝试根据系统启动时的一些信息设置要使用的默认iPassEnginer 以下代码成功地执行了此操作,但正在创建所选bean的两个实例: @Configuration public class BeanConfiguration { @Autowired private ShellUtilsService shellUt

我有一个名为IpAssginer的接口和两个实现IpAssginer的类,分别名为CloudIpAssginer和DHCPClientService

我正在尝试根据系统启动时的一些信息设置要使用的默认iPassEnginer

以下代码成功地执行了此操作,但正在创建所选bean的两个实例:

@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;
    }

}

你知道我如何做同样的事情,但只从所选bean创建一个实例吗?

你也可以使用
@bean
注释来创建Springbean,从
CloudiPassEnginer
DhcpClientService
类中删除原型注释,然后在
@Configuration
类中使用
@Bean
注释

@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;

    }

}

一个对我有效的解决方案:

我从上下文中排除了IpAssigner,它使用以下代码:

@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;
    }

    
}

我想你说的是“单身设计模式”