guice注入
Google Guice3.0:
http://code.google.com/p/google-guice/
maven地址:
Xml代码
- <dependency>
- <groupId>com.google.inject</groupId>
- <artifactId>guice</artifactId>
- <version>3.0</version>
- </dependency>
1:UserInfoDAO
Java代码
- package com.ljq.guice.test;
- public interface UserInfoDAO {
- public int update(int uid, String name);
- }
2: 实现类
Java代码
- package com.ljq.guice.test;
- public class UserInfoDAOImpl implements UserInfoDAO {
- public int update(int uid, String name) {
- System.out.println(" update name is success! ");
- return 1;
- }
- }
guice model:
Java代码
- package com.ljq.guice.test;
- import com.google.inject.Binder;
- import com.google.inject.Module;
- /**
- * guice ioc 注入
- * @author ljq
- */
- public class BindDAOModule implements Module {
- public void configure(Binder binder) {
- // 默认绑定是每次都new的,不是单例
- // 单例绑定 binder.bind(UserInfoDAO.class).to(UserInfoDAOImpl.class).in(Scopes.SINGLETON)
- // 一个接口不能绑定多个实现类
- // 可以binder.bind(UserInfoDAO.class).to(new UserInfoDAOImpl()); 绑定自己的实现
- // 可以在接口上使用@ImplementedBy(UserInfoDAO.class) 如果同时存在model,优先: 手动大于注解
- binder.bind(UserInfoDAO.class).to(UserInfoDAOImpl.class);
- }
- }
test:
Java代码
- package com.ljq.guice.test;
- import org.junit.Assert;
- import org.junit.Test;
- import com.google.inject.Guice;
- import com.google.inject.Injector;
- public class TestDAO {
- @Test
- public void testUserInfo() {
- //
- Injector injector=Guice.createInjector(new BindDAOModule());
- UserInfoDAO userInfo=injector.getInstance(UserInfoDAO.class);
- UserInfoDAO userInfo2=injector.getInstance(UserInfoDAO.class);
- Assert.assertEquals(userInfo.hashCode(), userInfo2.hashCode());
- }
- }
默认情况下,Guice每次在调用时都会返回一个新的实例,这种行为是可以通过作用域配置的,作用域允许复用对象实例。在一个应用服务的生命周期中,对象可能是单例的(@Singleton),也可能是一个回话的(@SessionScoped),也可能是一个请求的(@RequestScoped)。
饿汉式的单例可以很快揭示初始化问题,并确保最终用户获得一致的,直观的体验。懒汉式的单例保证了一个快速的编辑-完成-启动的开发周期,用这个Stage的枚举可以区分那种策略被使用:
PRODUCTION | DEVELOPMENT | |
.asEagerSingleton() | eager | eager |
.in(Singleton.class) | eager | lazy |
.in(Scopes.SINGLETON) | eager | lazy |
@Singleton | eager* | lazy |
//关于set get 注解等注入 以后再看;
DAO依赖guice框架的设计:
BaseDAO抽象一些共用的方法如setCache, getCache, clearCache 设置数据层缓存
可以用Memcached ,也可以用redis
DAOImpl可以对不同的DAO接口有不同的,把所有的注入放到BindDAOModule中
和业务层交互 ,只是需要通过DAOFactory就可以:
工程模式 通过传入不同的class获得对象,只是把用guice绑定了接口的实现而已:
Java代码
- public class DaoFactory {
- private static final Injector inj = Guice.createInjector(new BindDaoModule());
- public static <T> T getDao(Class<T> clazz) {
- return inj.getInstance(clazz);
- }
- }
转载于:https://my.oschina.net/mifans/blog/783485