天天看点

guice使用方法(1)

我说一下我在实际的项目中是怎么样使用guice的。会从entity-dao-action的路子走。

1.实体类

@Entity

@Table(name = "user")

public class User {

/**

*

*/

private static final long serialVersionUID = 5783459899984253122L;

private String id;

@Column(name = "username")

private String name;

@Id

@Column(length = 36, nullable = false)

@GeneratedValue(generator = "hibernate-uuid.hex")

@org.hibernate.annotations.GenericGenerator(name = "hibernate-uuid.hex", strategy = "uuid.hex")

public String getId() {

return id;

}

/**

* @param id

* the id to set

*/

public void setId(String id) {

this.id = id;

}

/**

* 得到用户名称

*/

public String getName() {

return name;

}

/**

* 设置用户名称

*

* @param name

*/

public void setName(String name) {

this. name = name;

}

}

2.Dao层

Public interface UserDao {

Public List<User> getAllUser();

}

Public Class UserDaoHibernate implements UserDao {

Public List<User> getAllUser() {

……省略。。

}

}

3.配置guice ,所有的自己写的Module都继承这个类

(1) 监听器 作用是初始化guice,并连接数据库

public class SystemStartupListener extends GuiceServletContextListener {

final static Logger log = LoggerFactory

.getLogger(SystemStartupListener.class);

private Injector _injector;

private SessionFactory _sf;

/*

* (non-Javadoc)

*

* @see

* javax.servlet.ServletContextListener#contextInitialized(javax.servlet

* .ServletContextEvent)

*/

@Override

public void contextInitialized(ServletContextEvent event) {

String serverPath=event.getServletContext().getRealPath("/upload");

log.info("OIA system startup...");

super.contextInitialized(event);

View view=new View(serverPath);

//build hibernate sessionFactory

Configuration conf = _injector.getInstance(Configuration.class);

_sf = conf.buildSessionFactory();

//LDAP sync data

LDAPUtils ldap = new LDAPUtils();

// ldap.batchInsertOrgDataFromLdap(_sf, ldap.getAllOrganization());

// ldap.batchInsertUserDataFromLdap(_sf, ldap.getAllEmployee());

// /**

// * 创建全文检索索引

// */

// if(!LuceneIndex.indexInit){

// LuceneUtils.createIndex(1);

// }

}

/*

* (non-Javadoc)

*

* @seejavax.servlet.ServletContextListener#contextDestroyed(javax.servlet.

* ServletContextEvent)

*/

@Override

public void contextDestroyed(ServletContextEvent event) {

super.contextDestroyed(event);

if(null != _sf) {

_sf.close();

log.info("Hibernate session factory is closed...");

}

log.info("OIA system shutdown...");

}

@Override

protected Injector getInjector() {

return _injector = Guice.createInjector(new WebServiceModule());

}

}

(2)

public class WebServiceModule extends ServiceModule {

final Logger log = LoggerFactory.getLogger(WebServiceModule.class);

private static Set<Module> modules = Collections.synchronizedSet(new HashSet<Module>());

private static Set<Class<?>> accessors = Collections.synchronizedSet(new HashSet<Class<?>>());

private static Set<Class<?>> annotatedClasses = Collections.synchronizedSet(new HashSet<Class<?>>());

protected void installModules() {

// 装配模块 , modules.add(Module);

// 自己写的那个module

modules.add(new UserModule());

}

/**

* 装配自己的Module,需继承AbstractModule

*/

@Override

protected final void config() {

installModules();

for(Module m : modules) {

if (log.isDebugEnabled())

log.debug("OIA install module: {}", m);

if (m instanceof AbstractWarpModule) {

if (((AbstractWarpModule) m).getAccessors()!= null)

accessors.addAll(((AbstractWarpModule) m).getAccessors());

annotatedClasses.addAll(((AbstractWarpModule) m).getAnnotatedClasses());

}

install(m);

}

}

/**

* 如果直接用接口实现Finder,则需要在此加入该接口

*/

@Override

protected final Iterator<Class<?>> getAccessors() {

return accessors.iterator();

}

/**

* 注入领域模型对象

*/

@Override

protected final Iterator<Class<?>> getAnnotatedClasses() {

return annotatedClasses.iterator();

}

}

(3)

public abstract class AbstractWarpModule extends AbstractModule {

/**

* 如果直接用接口实现Finder,则需要在此加入该接口

*/

protected List<Class<?>> getAccessors() {

return null;

}

/**

* 注入领域模型对象

*/

protected abstract List<Class<?>> getAnnotatedClasses();

}

(4).UserModule

public class UserModule extends AbstractWarpModule{

@Override

protected List<Class<?>> getAnnotatedClasses() {

List<Class<?>> list = new ArrayList<Class<?>>();

list.add(User.class);

return list;

}

@Override

protected void configure() {

staticParamOf();

}

/**

* 元数据相关

*/

protected void staticParamOf(){

bind(ISystemStaticParamServer.class).to(SystemStaticParamServerImp.class)

.asEagerSingleton();

}

}

5.struts2 action中的dao注入。关键字 @Inject

Public class UserAction extends ActionSupport {

@Inject

private UserDao userDao;

public String test() {

this.userDao.getAllUser(); // 这样就可以得到所有的user了。

return SUCCESS;

}

}

注:1.可以先将dao注入到entity中,在action中只注入entity就可以了,写法是一样的。自由发挥。2.别忘了把guice的包导入到工程中。