В этой части я продолжу демонстрировать интеграцию JSF, Guice и MyBatis. Пул соединений DBCP и база данных MYSQL используются на постоянном уровне. Посмотрите на часть 1 .
Интегрировать Google Guice с MyBatis
В предыдущем посте мы создали ServletContextListener. Теперь мы просто связываем BasicDataSourceProvider и JdbcTransactionFactory в методе contextInitialized.
GuiceContextListener.java
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | packageorg.borislam;importjava.util.Properties;importjavax.servlet.ServletContext;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;importorg.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;importorg.apache.log4j.xml.DOMConfigurator;importorg.borislam.mapper.StaffMapper;importorg.borislam.service.SimpleService;importorg.borislam.service.impl.SimpleServiceImpl;importorg.mybatis.guice.MyBatisModule;importorg.mybatis.guice.datasource.dbcp.BasicDataSourceProvider;importorg.mybatis.guice.datasource.helper.JdbcHelper;importcom.google.inject.Guice;importcom.google.inject.Injector;importcom.google.inject.Singleton;importcom.google.inject.name.Names;publicclassGuiceContextListener implementsServletContextListener {   publicvoidcontextDestroyed(ServletContextEvent servletContextEvent) {     ServletContext servletContext = servletContextEvent.getServletContext();     servletContext.removeAttribute(Injector.class.getName());   }   publicvoidcontextInitialized(ServletContextEvent servletContextEvent) {     Injector injector = Guice.createInjector(       newMyBatisModule() {        @Override        protectedvoidinitialize() {                  install(JdbcHelper.MySQL);         environmentId('development');                        bindDataSourceProviderType(BasicDataSourceProvider.class);         bindTransactionFactoryType(JdbcTransactionFactory.class);         Names.bindProperties(binder(), createServerProperties());         //add singleton service class         bind(SimpleService.class).to(SimpleServiceImpl.class).in(Singleton.class);          //add MyBatis Service class         addMapperClass(StaffMapper.class);         }        }       );     ServletContext servletContext = servletContextEvent.getServletContext();     servletContext.setAttribute(Injector.class.getName(), injector);     //log4J  DOMConfigurator.configure(    Thread.currentThread().getContextClassLoader()     .getResource('log4j.xml')    );   }   protectedstaticProperties createServerProperties() {         Properties myBatisProperties = newProperties();         myBatisProperties.setProperty('JDBC.host', 'localhost');         myBatisProperties.setProperty('JDBC.port', '3306');         myBatisProperties.setProperty('JDBC.schema', 'ttcoach');         myBatisProperties.setProperty('JDBC.username', 'root');         myBatisProperties.setProperty('JDBC.password', '');         myBatisProperties.setProperty('JDBC.autoCommit', 'false');         returnmyBatisProperties;   }} | 
Подготовьте свой класс картографа MyBatis и класс модели
Staff.java
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | packageorg.borislam.model;publicclassStaff { privateString code; privateString name; privateString sex; privateString tel; publicString getCode() {  returncode; } publicvoidsetCode(String code) {  this.code = code; } publicString getName() {  returnname; } publicvoidsetName(String name) {  this.name = name; } publicString getSex() {  returnsex; } publicvoidsetSex(String sex) {  this.sex = sex; } publicString getTel() {  returntel; } publicvoidsetTel(String tel) {  this.tel = tel; } } | 
StaffMapper.java
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | packageorg.borislam.mapper;importjava.util.List;importorg.apache.ibatis.annotations.Result;importorg.apache.ibatis.annotations.Results;importorg.apache.ibatis.annotations.Select;importorg.borislam.model.Staff;publicinterfaceStaffMapper {    finalString SELECT_ALL = 'SELECT * FROM FREELANCER';    finalString SELECT_BY_CODE = 'SELECT * FROM FREELANCER WHERE CODE = #{code}';    /**     * Returns the list of all Freelancer instances from the database.     * @return the list of all Freelancer instances from the database.     */    @Select(SELECT_ALL)    @Results(value = {        @Result(property='code', column='code'),        @Result(property='name', column='name'),        @Result(property='sex', column='sex'),        @Result(property='tel', column='tel')    })    List<Staff> selectAll();    /**     * Returns a Freelancer instance from the database.     * @param id primary key value used for lookup.     * @return A Freelancer instance with a primary key value equals to pk. null if there is no matching row.     */    @Select(SELECT_BY_CODE)    @Results(value = {            @Result(property='code', column='code'),            @Result(property='name', column='name'),            @Result(property='sex', column='sex'),            @Result(property='tel', column='tel')    })    Staff selectByCode(String code);} | 
Подготовьте свой класс обслуживания
SimpleService.java
| 1 2 3 4 5 | packageorg.borislam.service;publicinterfaceSimpleService { publicvoiddoSimpleThing();} | 
SimpleServiceImpl.java
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | packageorg.borislam.service.impl;importjava.util.List;importorg.borislam.mapper.StaffMapper;importorg.borislam.model.Staff;importorg.borislam.service.SimpleService;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importcom.google.inject.Inject;publicclassSimpleServiceImpl implementsSimpleService { privateStaffMapper staffMapper; Logger logger = LoggerFactory.getLogger(this.getClass()); @Inject publicvoidsetStaffMapper(StaffMapper staffMapper) {  this.staffMapper = staffMapper; } publicvoiddoSimpleThing() {  List<Staff> staffList = staffMapper.selectAll();  logger.debug('size 1: '+ staffList.size());  Staff staff = staffMapper.selectByCode('c001');  logger.debug('Code1 : '+ staff.getCode());  logger.debug('Name 1: '+ staff.getName());; }} | 
Подготовьте страницу поддержки JSF и XML-страницу
TestBean.java
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | packageorg.borislam.view;importjavax.faces.bean.ManagedBean;importjavax.faces.bean.SessionScoped;importjavax.inject.Inject;importorg.borislam.service.SimpleService;importorg.borislam.service.TestService;@ManagedBean@SessionScopedpublicclassTestBean extendsBasePageBean { privateSimpleService sService; @Inject publicvoidsetsService(SimpleService sService) {  this.sService = sService; } publicString doTest(){  System.out.println('test 1 inside backing bean...');  sService.doSimpleThing();  return''; } publicString doTest2(){  System.out.println('test 2 inside backing bean...');  sService.doSimpleThing();  return''; }} | 
index.xhtml
| 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 | <h:head><style>.ui-widget, .ui-widget .ui-widget {font-size: 80% !important;}</style></h:head><h:body><h:form> <h:outputTextvalue='#{msg['website.title']}' />    <p:calendarid='popupButtonCal'showOn='button'/>    <p:commandButtonvalue='TEST2'action='#{testBean.doTest}'/> <p:editor/> <br/></h:form></h:body></html> | 
  Это сделано!  Теперь вы можете написать свое приложение JSF на основе этого фреймворка. 
  Ссылка: облегченная платформа веб-приложений: PrimeFaces (JSF) + Guice + MyBatis (ЧАСТЬ 2) от нашего партнера по JCG Бориса Лэма в блоге Programming Peaceful .