春季使用配置文件控制bean



我有1个接口和2个类实现这个接口。

public interface Service{
void process();
}
@Component("ServiceA")
public class ServiceA implements Service{
public void process(){
// some code
}
}
@Component("ServiceB")
public class  ServiceB implements Service{
public void process(){
// some code
}
}

我不使用@Qualifier。我想使用配置文件代替。例如

# default serviceA
service.B.enable=true

我在另一个服务中使用了@Autowire的Service接口

@Service
public class MainService{
@Autowired
public Service service;
}

我该怎么做呢?

可以在ServiceA和ServiceB类上面设置一个条件注释-@ConditionalOnProperty

配置:

my.service=ServiceA

修改代码:

public interface Service{
void process();
}
@Component("ServiceA")
@ConditionalOnProperty(prefix = "my", name = "service", havingValue = "ServiceA")
public class ServiceA implements Service{
public void process(){
// some code
}
}
@Component("ServiceB")
@ConditionalOnProperty(prefix = "my", name = "service", havingValue = "ServiceB")
public class  ServiceB implements Service{
public void process(){
// some code
}
}

最新更新