当前位置: 首页 > 面试题库 >

集成jsf,spring,hibernate。如何将Spring bean注入JSF管理的bean中?

上官彬
2023-03-14
问题内容

我正在使用框架JSF 2.1,Spring 3.1.1.Release,Hibernate 3.2.1进行Java
EE项目。现在我正处于整合这三个方面的阶段。构建成功,我使用了tomcat服务器7。但是我在首页上看到了这个异常

Etat HTTP 500 -

type Rapport d''exception

message

description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.

exception

javax.servlet.ServletException
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
cause mère

java.lang.NullPointerException
    controller.AnneeBean.getListeAnnees(AnneeBean.java:15)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:601)
    javax.el.BeanELResolver.getValue(BeanELResolver.java:87)
    com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    org.apache.el.parser.AstValue.getValue(AstValue.java:183)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    javax.faces.component.UIData.getValue(UIData.java:731)
    javax.faces.component.UIData.getDataModel(UIData.java:1798)
    javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
    javax.faces.component.UIData.setRowIndex(UIData.java:473)
    com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
note La trace complète de la cause mère de cette erreur est disponible dans les fichiers journaux de Apache Tomcat/7.0.42.

hibernatehibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/base?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <mapping resource="net/vo/Annee.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.reveng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="base"/>
  <table-filter match-name="annee"/>
</hibernate-reverse-engineering>

AnneeDao.java

package dao;

import java.util.List;
import net.vo.Annee;

public interface AnneeDao {
    public List getAllAnnees();
    public Annee getAnnee(Integer id);
    public void insert(Annee annee);
    public void update(Annee annee);
    public void delete(Integer id);
}

AnneeHibernateDao.java

package dao;

import java.util.List;
import net.vo.Annee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class AnneeHibernateDao implements AnneeDao{
    private List<Annee> listeAnnees;
    private Annee annee;
    public void init()
    {
        System.out.println("Méthode d'initiation");
    }
    @Override
    public List getAllAnnees() {
        Session session=HibernateUtil.getSession();
        try
        {
            session.beginTransaction();
            listeAnnees = session.createQuery("from Annee").list();
            return listeAnnees;
        }
        catch(HibernateException e)
        {
            throw e;
        }
        finally
        {
            session.close();
        }
    }

    @Override
    public Annee getAnnee(Integer id) {
       Session session = HibernateUtil.getSession();
       try
       {
           session.beginTransaction();
           Query q = session.createQuery("from Annee as a where a.annee=" + id);
           return (Annee) q.uniqueResult();
       }
       finally
       {
           session.close();
       }
    }

    @Override
    public void insert(Annee annee) {

      Session session = HibernateUtil.getSession();
      Transaction tx=null;
      try
      {
          tx = session.beginTransaction();
          session.save(annee);
          tx.commit();         
      }
      catch(RuntimeException e)
      {
          if(tx != null) 
            {
                tx.rollback();
            }
          throw e;
      }
      finally
      {
          session.close();
      }
    }

    @Override
    public void update(Annee annee) {
        Session session = HibernateUtil.getSession();
        Transaction tx=null;
        try
        {
            tx=session.beginTransaction();
            session.update(annee);
            tx.commit();
        }
         catch(RuntimeException e)
         {
           if(tx != null) 
            {
                tx.rollback();
            }
            throw e;
         }
         finally
         {
            session.close();
         }
    }

    @Override
    public void delete(Integer id) {
       Session session = HibernateUtil.getSession();
       Transaction tx = null;
       try
       {
           tx=session.beginTransaction();
           annee = (Annee) session.get(Annee.class,id);
           session.delete(annee);
           tx.commit();
       }
       catch(RuntimeException e)
         {
            if(tx != null) 
            {
                tx.rollback();
            }
            throw e;
         }
         finally
         {
            session.close();
         }
    }


}

HibernateUtil.java

package dao;

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author images
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}

Pojo文件

Annee.java

package net.vo;

public class Annee  implements java.io.Serializable {


     private int annee;

    public Annee() {
    }

    public Annee(int annee) {
       this.annee = annee;
    }

    public int getAnnee() {
        return this.annee;
    }

    public void setAnnee(int annee) {
        this.annee = annee;
    }




}

映射文件:Annee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 13 mai 2014 18:23:22 by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="net.vo.Annee" table="annee" catalog="base">
        <id name="annee" type="int">
            <column name="annee" />
            <generator class="assigned" />
        </id>
    </class>
</hibernate-mapping>

springAnneeMetier.java

package model.services;

import java.util.List;

public interface AnneeMetier {
    public List getAllAnnees();
}

AnneeMetierImpl.java

package model.services;

import dao.AnneeDao;
import java.util.List;
import net.vo.Annee;

public class AnneeMetierImpl implements AnneeMetier{

    private AnneeDao anneeDao;

    @Override
    public List getAllAnnees() {
            return anneeDao.getAllAnnees();
    }

    public void setAnneeDao(AnneeDao anneeDao) {
        this.anneeDao = anneeDao;
    }

    public AnneeDao getAnneeDao() {
        return anneeDao;
    }

}

JSF AnneeBean.java

package controller;

import java.util.List;
import model.services.AnneeMetier;
import net.vo.Annee;

public class AnneeBean {

    private AnneeMetier anneeMetier;

    private List<Annee> listeAnnees;

    public List getListeAnnees() {
        listeAnnees = anneeMetier.getAllAnnees();
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
       <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   <listener>
      <listener-class>
         org.springframework.web.context.request.RequestContextListener
      </listener-class>
   </listener>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
       xmlns:context="http://www.springframework.org/schema/context/spring-context-3.1.xsd"
       xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
          http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/aop/spring-aop-3.1.xsd/spring-spring-aop-3.1.xsd-3.1.1.RELEASE.xsd
          http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/context/spring-context-3.1.xsd/spring-spring-context-2.5.xsd-3.1.1.RELEASE.xsd
          http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/tx/spring-tx-3.1.xsd/spring-spring-tx-3.1.xsd-3.1.1.RELEASE.xsd
">
     <bean id="anneeDao" class="dao.AnneeHibernateDao"></bean>
    <bean id="anneeMetier" class="model.services.AnneeMetierImpl">
        <property name="anneeDao" ref="anneeDao"/>  
    </bean>

</beans>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>

<!-- =========== FULL CONFIGURATION FILE ================================== -->

<faces-config version="2.1"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">

<application>
   <variable-resolver>
      org.springframework.web.jsf.DelegatingVariableResolver
   </variable-resolver>
</application>
 <managed-bean>
      <managed-bean-name>anneeBean</managed-bean-name>
      <managed-bean-class>controller.AnneeBean</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
   </managed-bean> 
</faces-config>

index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <h:dataTable var="annees" value="#{anneeBean.listeAnnees}">
                    <p:column headerText="Annee">
                        <h:outputText value="#{annee.annees}"/>
                    </p:column>
                </h:dataTable>
    </h:body>
</html>

请你能帮我,我会很感激的

编辑: 这是更新的堆栈跟踪

mai 14, 2014 1:14:41 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/testJSF_Spring_Hibernate] threw exception [Erreur lors de linjection de ressources dans le bean géré anneeBean] with root cause
java.lang.NullPointerException
    at model.services.AnneeMetierImpl.getAllAnnees(AnneeMetierImpl.java:17)
    at controller.AnneeBean.init(AnneeBean.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokeAnnotatedMethod(WebContainerInjectionProvider.java:117)
    at com.sun.faces.vendor.WebContainerInjectionProvider.invokePostConstruct(WebContainerInjectionProvider.java:99)
    at com.sun.faces.mgbean.BeanBuilder.invokePostConstruct(BeanBuilder.java:223)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:105)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.faces.el.ChainAwareVariableResolver.resolveVariable(ChainAwareVariableResolver.java:107)
    at org.springframework.web.jsf.DelegatingVariableResolver.resolveOriginal(DelegatingVariableResolver.java:123)
    at org.springframework.web.jsf.DelegatingVariableResolver.resolveVariable(DelegatingVariableResolver.java:108)
    at com.sun.faces.el.VariableResolverChainWrapper.getValue(VariableResolverChainWrapper.java:115)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:72)
    at org.apache.el.parser.AstValue.getValue(AstValue.java:161)
    at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:731)
    at javax.faces.component.UIData.getDataModel(UIData.java:1798)
    at javax.faces.component.UIData.setRowIndexWithoutRowStatePreserved(UIData.java:484)
    at javax.faces.component.UIData.setRowIndex(UIData.java:473)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:81)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:820)
    at javax.faces.component.UIData.encodeBegin(UIData.java:1118)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1754)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

编辑2: 这是AnneeBean类

package controller;

import java.util.List;
import javax.annotation.PostConstruct;
import model.services.AnneeMetier;
import model.services.AnneeMetierImpl;
import net.vo.Annee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("view")
public class AnneeBean {

    @Autowired
    private AnneeMetier anneeMetier;

    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        anneeMetier = new AnneeMetierImpl();
        listeAnnees = anneeMetier.getAllAnnees();
    }
    public List getListeAnnees() {
        listeAnnees = anneeMetier.getAllAnnees();
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }

}

编辑3: index.xhtml

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
 <h:form>
     <p:dataTable var="listeAnnees" value="#{anneeBean.listeAnnees}">
                <p:column headerText="Annee">
                    <h:outputText value="#{listeAnnees.annee}"/>
                    </p:column>
            </p:dataTable>        
        </h:form>
    </h:body>
</html>

问题答案:

The naive solution for non-JSF developers would be to simply initialize the
variables inside the getter to resolve the null value in the attributes.
This is:

public List getListeAnnees() {
    listeAnnees = getAnneeMetier().getAllAnnees();
    return listeAnnees;
}

public AnneeMetier getAnneeMetier() {
    if (anneeMetier == null) {
        anneeMetier = new AnneeMetierImpl();
    }
    return anneeMetier;
}

But this may generate lot of overhead from server in case
AnneeMetier#getAllAnnees() retrieves the data from database. This is
explained here: Why JSF calls getters multipletimes

To solve this, you do two things:

  1. Define the right scope of your bean.
  2. Initialize the necessary data for work using @PostConstruct annotated method.

And this would result in:

  1. Defining the scope as @ViewScoped (explained in the link above).
  2. Initializing listeAnnees in @PostConstruct method.
  3. Remove any business logic from getters/setters

So the code would look like this:

@ManagedBean
@ViewScoped
public class AnneeBean {
    private AnneeMetier anneeMetier;
    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        anneeMetier = new AnneeMetierImpl();
        listeAnnees = anneeMetier.getAllAnnees();
    }

    public List getListeAnnees() {
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }

    public AnneeMetier getAnneeMetier() {
        return anneeMetier;
    }

    public void setAnneeMetier(AnneeMetier anneeMetier) {
        this.anneeMetier = anneeMetier;
    }
}

BUT since you’re trying to integrate JSF with Spring, you have to take
into account that Spring has not yet full support of JSF 2 @ViewScoped
annotation. For this case, you
have/need to implement it yourself. There are plenty examples on the net about
this, and looks that the most popular is from
Cagatay’s. In this way, you’ll be able to gain power
from both sides. And your bean will look like this:

@Component
@Scope("view")
public class AnneeBean {
    @Autowired
    private AnneeMetier anneeMetier;
    private List<Annee> listeAnnees;

    @PostConstruct
    public void init() {
        listeAnnees = anneeMetier.getAllAnnees();
    }

    public List getListeAnnees() {
        return listeAnnees;
    }

    public void setListeAnnees(List listeAnnees) {
        this.listeAnnees = listeAnnees;
    }
}

Since you’re learning Spring, the best bet would be to enable component scan
and use annotations to configure your spring beans. Do the following:

  • Remove any bean configuration in applicationContext.xml.
  • Add this configuration to enable bean scan annotations:
        <!-- 
        These will enable component scan by annotation configuration
        rather than XML configuration. One per package
    -->
    <context:component-scan base-package="dao" />
    <context:component-scan base-package="model.services" />

Or if all your classes are inside one root package.

    <!--
    Assuming there's a root package for your packages like this
<context:component-scan base-package="com.myproject.dao" />
<context:component-scan base-package="com.myproject.model.services" />
-->
<context:component-scan base-package="com.myproject" />
  • Start configuring your Spring managed beans by annotations:
        @Repository
    public class AnneeHibernateDao implements AnneeDao{
        //...
    }

    @Service
    public class AnneeMetierImpl implements AnneeMetier{
        @Autowired
        private AnneeDao anneeDao;
        //...
    }

Compile your project and run it.



 类似资料:
  • 问题内容: 我了解托管bean的工作方式类似于控制器,因为你的唯一任务是将“视图层”与模型“链接”。 要将bean用作托管bean,我必须声明注释,这样我就可以直接与bean通信JSF。 如果要在此managedBean中注入某些组件(来自Spring),则有两种可能的方法: 在ManagedBean中选择属性(例如“ BasicDAO dao”),然后在该属性上方进行声明。这样做,我是将”bas

  • 我理解托管bean的工作方式类似于控制器,因为您唯一的任务是将视图层与模型“链接”。 要将bean用作托管bean,我必须声明注释,这样我就可以直接与bean进行JSF通信。 如果我想在这个managedBean中注入一些组件(来自Spring),我有两种可能的方法: > 选择ManagedBean中的属性(如“basicdao dao”)并在该属性上方声明。为此,我在ManagedBean中注入

  • 我正在开发一个遗留的JSF应用程序,我们正在慢慢地将其移植到Spring MVC。我们正在使用Spring Security来控制登录信息。在用户登录之后,JSF页面全局地实例化一个在任何地方都使用的会话作用域bean。我想更改应用程序,这样我们就可以先进入用Spring MVC开发的页面。 我尝试的一种方法是将bean转换为spring bean,并将其注入JSF,但不幸的是,这需要对bean进

  • 问题内容: 我在演示应用程序中使用JSF2 + Spring3.1 + Hibernate4,我将要使用批注创建会话工厂,但我的DAO类未在Jsf Managed Bea类中初始化,因此我得到了Null指针异常。我的 applicationContext.xml UserDAO.java类 和我的ManagedBean类 现在在Managedbean方法中,DAO对象为null,并且我得到了Nul

  • 我有一个JSF的问题,CDI项目。我做了大量研究,发现在CDI中没有注释。我用对话框解决基于ajax的页面的问题。我想将变量从DataTable传递到dialog。为此,我不能使用bean,因为在请求结束后会丢弃值。有人能帮我解决吗?我不能使用,但这是一个糟糕的做法。或者只保存这一个变量到会话谁知道。你们能给我一些提示如何优雅地解决这个问题吗? 以下是错误消息:

  • 我在演示应用程序中使用了JSF2+Spring3.1+Hibernate4,我想使用注释来创建会话工厂,但是我的DAO类没有在Jsf托管Bea类中初始化,所以我得到了空指针异常。我的ApplicationContext.xml 现在,在Managedbean方法中,DAO对象为null,我得到的是null指针异常