Using Guice, how do I add superclass constructor options?

Possible duplicate:
Guice with parents

class Book{string title;} class ChildrensBook extends Book{} class ScienceBook extends Book{} 

I want to add the names of books to subclasses, for example, childrensBook should be given the heading "Alice in Wonderland", and ScienceBook should get "On the Origin of Species." How can I accomplish this with Guice?

(Note that I do not want to overwrite the title field in the subclass)

+6
source share
2 answers

Previously asked and answered here :

Buried in the Minimize Mutability section of Guice Best Practices, you will find this guide:

Subclasses should call super() with all the dependencies. This makes the constructor injection cumbersome, especially since the introduced base changes the class.

In practice, here's how to do this using constructor injection:

 public class TestInheritanceBinding { static class Book { final String title; @Inject Book(@Named("GeneralTitle") String title) { this.title = title; } } static class ChildrensBook extends Book { @Inject ChildrensBook(@Named("ChildrensTitle") String title) { super(title); } } static class ScienceBook extends Book { @Inject ScienceBook(@Named("ScienceTitle") String title) { super(title); } } @Test public void bindingWorked() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(String.class). annotatedWith(Names.named("GeneralTitle")). toInstance("To Kill a Mockingbird"); bind(String.class). annotatedWith(Names.named("ChildrensTitle")). toInstance("Alice in Wonderland"); bind(String.class). annotatedWith(Names.named("ScienceTitle")). toInstance("On the Origin of Species"); } }); Book generalBook = injector.getInstance(Book.class); assertEquals("To Kill a Mockingbird", generalBook.title); ChildrensBook childrensBook = injector.getInstance(ChildrensBook.class); assertEquals("Alice in Wonderland", childrensBook.title); ScienceBook scienceBook = injector.getInstance(ScienceBook.class); assertEquals("On the Origin of Species", scienceBook.title); } } 
+5
source

It is probably best to write subclass constructors with various parameter annotations - something like

 class ChildrensBook extends Book { @Inject ChildrensBook (@AliceInWonderland String title) { super(title); } } 
0
source

Source: https://habr.com/ru/post/906912/


All Articles