Total Pageviews

2018/02/05

[Google Guice] Dependency Injection Example

Google Guice is the framework to automate the dependency injection in applications. Google Guice is one of the leading frameworks whose main work is to provide automatic implementation of dependency injection. 



How-To
Step 1. Add dependency in your pom.xml
1
2
3
4
5
    <dependency>
        <groupId>com.google.inject</groupId>
        <artifactId>guice</artifactId>
        <version>4.1.0</version>
    </dependency>


Step 2. Create a service class to retrieve a person's contact people
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package albert.practice.guice;

import java.util.List;

import com.google.common.collect.ImmutableList;
import com.google.inject.Singleton;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Singleton
public class ContactService {

    public List<Contact> getContacts(String id) {
        log.debug("person id is " + id);
        return ImmutableList.of(new Contact("Mandy", "0912111111"), new Contact("Dad", "0911111111"),
                new Contact("Mom", "0922222222"));
    }

}


Step 3. Create a resource to inject service class and retrieve person's contact people 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package albert.practice.guice;

import java.util.List;

import com.google.inject.Inject;


public class PersonResource {
 
    @Inject
    private ContactService contactService;
    
    public List<Contact> getContacts(String id) {
        return contactService.getContacts(id);
    }
    
}



Step 4. Create a test class
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package albert.practice.guice;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import com.google.inject.Guice;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PersonResourceTest {
 
    private PersonResource personResouce;
    
    @Before
    public void setup() {
        personResouce = Guice.createInjector().getInstance(PersonResource.class);
    }
    
    @Test
    public void testGetContacts() {
        List<Contact> contacts = personResouce.getContacts("123");
        contacts.stream().forEach(c -> log.debug(c.toString()));
        
        assertEquals(3, contacts.size());
    }
}
    





No comments: