[英]Control bean with config file in spring
我有 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
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.