English 中文(简体)
Guice - Inbuilt Bindings
  • 时间:2024-12-22

Google Guice - Inbuilt Bindings


Previous Page Next Page  

Guice provides inbuilt binding for java.util.logging.Logger class. Logger s name is automatically set to the name of the class into which the Logger is injected. See the example below.

Example

Create a java class named GuiceTester.

GuiceTester.java


import java.util.logging.Logger;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

pubpc class GuiceTester {
   pubpc static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck();
   } 
}

class TextEditor {
   private Logger logger;

   @Inject
   pubpc TextEditor( Logger logger) {
      this.logger = logger;
   }

   pubpc void makeSpellCheck(){
      logger.info("In TextEditor.makeSpellCheck() method");
   } 
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() {
   } 
}

Output

Compile and run the file, you will see the following output.


Dec 20, 2017 12:51:05 PM TextEditor makeSpellCheck
INFO: In TextEditor.makeSpellCheck() method
Advertisements