Luminous: @guice dependency injection (VI)

Luminous Preamble:

 

Love a person, there is only love is not enough, if you want to be in love forever, such a man must be worthy of their own to look up to. The people you love him, you must have a few special appreciation, such as knowledgeable, talented, motivated. You'll find him a steady stream of good, as always inexhaustible supply of water, some of his good qualities, and you will feel proud, proud, so that men and women love is equal, your love it will not dry up.

 

 

 

 

 

text:

First of all: how to inject Provider

DatabaseConnection dbConn
Provider< DatabaseConnection > dbConnProvider

这里需要注意:Guice会考虑对象生命周期

所以需要时可以自己实现Provider

Next: Naming injection

@Inject @Named(“dbSpec”) private String dbSpec;
@Inject @LogFileName private String logFileName;
使用@Named:参数来自配置文件或命令行、或者为了开发方便
使用属性:通常采用此方法

We write a test class, that by testing

 

package Test;

/*
*
 * @title SessionManagerTest
 * @describe  编写一个测试类,用于测试一下@providers
 * @author hy
 * @version
 * @date 2019/6/20
 *
 */


import com.Test1.impl.ServerModule;
import com.Test1.impl.SessionManager;

import com.google.inject.Guice;

import static org.junit.Assert.assertNotEquals;



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

import javax.inject.Inject;


public class SessionManagerTest {

    @Inject
    SessionManager sessionManager;

    @Before
    public void setup(){
        Guice.createInjector(new ServerModule())
                .injectMembers(this);

    }

    @Test
    public void testGetSessionId() throws InterruptedException{

        Long sessionId1 = sessionManager.getSessionId();
        Thread.sleep(3000);

        Long sessionId2 = sessionManager.getSessionId();
        assertNotEquals(sessionId1.longValue(),sessionId2.longValue());

    }


}

 

 

Guess you like

Origin blog.csdn.net/weixin_41987706/article/details/92962897