Home > database >  Control bean with config file in spring
Control bean with config file in spring

Time:12-23

I have 1 interface and 2 class implement this interface.

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

I don't use @Qualifier. I want to use config file instead. for example

# default serviceA
service.B.enable=true

And i use Service interface with @Autowire in another service.

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

How can I do that?

CodePudding user response:

You can set a condition annotation - @ConditionalOnProperty above ServiceA and ServiceB classes.

Config:

my.service=ServiceA

Changes in code:

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
    }
}
  • Related