Pavlo Plynko
Pavlo Plynko

Reputation: 586

How, depending on the settings in the property file, force service to use a particular repository?

I set VM options to -Dmyapp.conf=config/my.properties. I need to use this file content to select which repository to use. I use SpringBoot.

There is service, now it gives Could not autowire. There is more than one bean of 'MyRepository' type:

@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private MyRepository repository;
...}

Repositories:

public interface MyRepository  {...}

@Repository
public class MyRepositoryImpl01 implements MyRepository  {...}

@Repository
public class MyRepositoryImpl02 implements MyRepository  {...}

Upvotes: 0

Views: 102

Answers (2)

Rafal G.
Rafal G.

Reputation: 4432

I would actually consider having this logic in some Java Config (a class annotated with @Configurtation) than in both (or possibly N) repositories.

You could use @ConditionalOnProperty and in this Java Config you would encapsulate entire logic of this "repository selection". This would be a benefit since you would only have 1 bean of the specified type, which in turn could be useful if your repositories connect to databases that are not available for certain configuration options.

Upvotes: 0

Adam Siemion
Adam Siemion

Reputation: 16039

You can use Spring profiles for that purpose.

@Profile("profile1")
@Repository
public class MyRepositoryImpl01 implements MyRepository  {...}

@Profile("profile2")
@Repository
public class MyRepositoryImpl02 implements MyRepository  {...}

Then in the property file you need: spring.profiles.active=profile1 or spring.profiles.active=profile2.

Upvotes: 2

Related Questions