Reed
Reed

Reputation: 1261

How do I autowire a repository which has primitive type dependency injection?

I have three text files, they all contain data of the same type, but data is stored differently in each file.

I want to have one interface:

public interface ItemRepository() {
    List<Item> getItems();
}

And instead of creating three implementations I want to create one implementation and use dependency injection to inject a path to the text file and an analyser class for each text file:

public class ItemRepositoryImpl() implements ItemRepository {
    Analyser analyser;
    String path;

    public ItemRepositoryImpl(Analyser analyser, String path) {
        this.analyser = analyser;
        this.path = path;
    }

    public List<Item> getItems() {
        // Use injected analyser and a path to the text file to extract the data
    }
}

How do I wire everything and inject the ItemRepositoryImpl into my controller?

I know I could simply do:

@Controller
public class ItemController {

    @RequestMapping("/items1")
    public List<Item> getItems1() {
        ItemRepository itemRepository = new ItemRepositoryImpl(new Analyser1(), "file1.txt");
        return itemRepository.getItems();
    }

    @RequestMapping("/items2")
    public List<Item> getItems1() {
        ItemRepository itemRepository = new ItemRepositoryImpl(new Analyser2(), "file2.txt");
        return itemRepository.getItems();
    }

    @RequestMapping("/items3")
    public List<Item> getItems1() {
        ItemRepository itemRepository = new ItemRepositoryImpl(new Analyser3(), "file3.txt");
        return itemRepository.getItems();
    }

}

But I don't know how to configure Spring to autowire it.

Upvotes: 0

Views: 201

Answers (1)

L.H
L.H

Reputation: 81

You can achieve it in many different ways and it probably depends on your design.

One of them can be initialising 3 different analyzers in spring context and wiring all the three analyzers in ItemRepositoryImpl using '@Qualifier' annotation. With the help of an extra method parameter, ItemRepositoryImpl can decide which analyzer it should route the requests to.

For the path variable also you can follow a similar approach.

If your question is specific about how to wire the primitive type in the bean, check this post . It specifies how to initialize a String variable in spring context.

Upvotes: 1

Related Questions