web-dev-qa-db-fra.com

NoUniqueBeanDefinitionException: pas de bean qualifiant de type ... i défini, bean correspondant unique attendu mais trouvé 2

Nous avons un peu cherché à la fois sur Internet et sur nos cours de poche, mais nous n'arrivons pas à trouver une solution à notre problème:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [services.GebruikerDAO] is defined: expected single matching bean but found 2: gebruikerDAO,GebruikerDAO
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:863)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:486)
... 58 more

Pour dessiner quelques informations de base: nous devons créer un petit site Web en utilisant les pages jsp Java et autres, ainsi que Spring Security et Maven en utilisant une base de données pour obtenir des informations et rechercher des informations. Après seront tous nos fichiers.

Voici notre classe GebruikerDAO:

package services;
import domein.Gebruiker;

public interface GebruikerDAO extends GenericDao<Gebruiker>{

    public Gebruiker getGebruikerByStamnummer(String stamnummer);

}

Voici notre classe JpaGebruikerDao:

@Repository("gebruikerDAO")
public class JpaGebruikerDao extends GenericDaoJpa<Gebruiker> implements GebruikerDAO{

    @PersistenceContext
    private EntityManager em;

    public JpaGebruikerDao()
    {
        super(Gebruiker.class);
    }

    /*@Override
    @Transactional
    public List<Gebruiker> findAll() {
        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery<Gebruiker> criteriaQuery = criteriaBuilder.createQuery(Gebruiker.class);

        Root<Gebruiker> gebruiker = criteriaQuery.from(Gebruiker.class);

        criteriaQuery.orderBy(criteriaBuilder.desc(gebruiker.get(Gebruiker_.familienaam)));

    // JPQL select 
        criteriaQuery.select(gebruiker);

        TypedQuery<Gebruiker> query = em.createQuery(criteriaQuery);
        return query.getResultList();
    }*/

    // CRUD methods
    @Override
    @Transactional
    public Gebruiker update(Gebruiker gebruiker) {
        return em.merge(gebruiker);
    }

    @Override
    @Transactional(readOnly = true)
    public Gebruiker get(String id) {
        return em.find(Gebruiker.class, id);
    }

    @Override
    @Transactional
    public void insert(Gebruiker gebruiker) {
        em.persist(gebruiker);
    }

    @Override
    @Transactional
    public void delete(Gebruiker gebruiker) {
        em.remove(em.merge(gebruiker));
    }

    @Override
    public Gebruiker getGebruikerByStamnummer(String stamnummer) {
        return get(stamnummer);
    }
}

Voici notre classe de contrôleurs:

@Controller
public class PlanningController {

    @Autowired
    @Qualifier("GebruikerDAO")
    private GebruikerDAO gebruikerDao;

    @RequestMapping(value = "/planning", method = RequestMethod.GET)
    public String listGuest(Model model)
    {
        List<Gebruiker> gebruikerlijst = gebruikerDao.findAll();
        List<Student> studentlijst = new ArrayList<>();

        for (Gebruiker s : gebruikerlijst) {
            if (s instanceof Student){
                Student student = (Student)s;
                if(student.getLokaal() != null)
                {
                    studentlijst.add(student);
                }
            }
        }
        // there is more but it just checks for if a timeslot is available in our planning

Voici notre fichier de sécurité printanière:

<beans:beans xmlns="http://www.springframework.org/schema/security"
         xmlns:beans="http://www.springframework.org/schema/beans"
         xmlns:p="http://www.springframework.org/schema/p"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
            http://www.springframework.org/schema/security
            http://www.springframework.org/schema/security/spring-security-3.1.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

<beans:import resource="applicationContext.xml"/>

<http auto-config="true">
    <intercept-url pattern="/admin*" access="hasAnyRole('ROLE_Student', 'ROLE_Promotor', 'ROLE_Coordinator')"/>
    <logout logout-success-url="/planning.htm"/>
    <access-denied-handler ref="accessDeniedHandler"/>
    <remember-me/>
</http>

<authentication-manager>
    <authentication-provider>
        <password-encoder hash="sha-256"/>
        <jdbc-user-service data-source-ref="dataSource"
                           users-by-username-query="select StamNummer, WachtwoordEncrypted, 'true' as enabled from gebruiker where StamNummer=?"
                           authorities-by-username-query="select StamNummer, Type as authority from gebruiker where StamNummer=?"
                           role-prefix="ROLE_"
        />
    </authentication-provider>
</authentication-manager>

<beans:bean class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>

Ceci est notre fichier applicationContext:

<?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:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   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 http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <bean name = "GebruikerDAO" class="services.JpaGebruikerDao"/>
</beans>

Voici notre fichier dispatcher-servlet:

<?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:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:jee="http://www.springframework.org/schema/jee"
   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
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd">   

<mvc:annotation-driven />
<context:component-scan base-package="controller"/>
<context:component-scan base-package="services"/>

<bean id="accessDeniedHandler" class="handler.MyAccessDeniedHandler">
    <property name="accessDeniedUrl" value="403"/>
</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/bachelorproef"/> <!--  jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull-->
    <property name="username" value="root"/>
    <property name="password" value="root"/>
</bean>
<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>domein</value>
        </list>
    </property>
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" /> 
            <property name="generateDdl" value="true" />
            <property name="database" value="MYSQL"/>
        </bean>
    </property>
</bean>

<bean id="transactionManager" 
      class=" org.springframework.orm.jpa.JpaTransactionManager ">
    <constructor-arg ref="entityManagerFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />
</beans>

Ceci est notre fichier web.xml:

<web-app id="WebApp_ID" version="2.4" xmlns="http://Java.Sun.com/xml/ns/j2ee"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://Java.Sun.com/xml/ns/j2ee http://Java.Sun.com/xml/ns/j2ee/web-   app_2_4.xsd">
<display-name>Spring MVC Application</display-name> 
<servlet>
    <servlet-name>dispatcher</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <load-on-startup>1</load-on-startup> 
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name> 
    <url-pattern>/</url-pattern> 
</servlet-mapping>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener>
<context-param>
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/dispatcher-servlet.xml, 
                            /WEB-INF/spring-security2.xml
    </param-value> 
</context-param> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping>
</web-app>

Voici notre classe Gebruiker:

@Entity
@Table(name = "gebruiker")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "Type")
public abstract class Gebruiker implements Serializable {

@Id
@Column(name = "StamNummer")
private String stamNummer;
@Column(name = "Familienaam")
private String familienaam;
@Column(name = "Voornaam")
private String voornaam;
@Column(name = "Email")
private String email;
@Column(name = "Wachtwoord")
private String wachtwoord;
@Column(name = "Campus")
private String campus;
@Transient
private String naam;

public Gebruiker() {

}
(+ some extra getters, setters and generatePassword methods)

Voici notre classe d'étudiants:

@Entity
@DiscriminatorValue("Student")
public class Student extends Gebruiker{

@ManyToOne
private Promotor promotor;

@OneToOne
@JoinColumn(name = "HuidigDossier_DossierId")
private Dossier dossier;

@Temporal(TemporalType.TIMESTAMP)
private Date datumPresentatie;  

private String lokaal;
(+ some getters, setters and toString)

Ceci est notre classe de promoteur:

@Entity
@DiscriminatorValue("Promotor")
public class Promotor extends Gebruiker {

    @OneToMany(mappedBy="promotor")
    List<Student> studenten;

    public Promotor(){
         studenten = new ArrayList<>();
    }

    public List<Student> getStudenten() {
        return studenten;
    }

    public void setStudenten(List<Student> studenten) {
        this.studenten = studenten;
    }

}

Voici notre classe BPCoordinator: 

@Entity
@DiscriminatorValue("Coordinator")
public class BPCoordinator extends Gebruiker{

    public BPCoordinator(){

    }
}

Je sais qu'il y a beaucoup d'informations à trouver si l'erreur NoUniqueBeanDefinitionException se produit, mais cela se réfère presque toujours au entityManager, ici il dit que gebruikerDAO et GebruikerDAO ou quelque chose sont trouvés et nous n'avons aucune idée d'où il les obtient ou pourquoi se produit. La plupart de ce code a été presque purement copié-collé d’autres projets scolaires et de codes de poche (notre cours nous a été donné par nos lecteurs)

Idées où et comment résoudre le problème serait incroyable.

11
Tempuslight

Supprimez <bean name = "GebruikerDAO" class="services.JpaGebruikerDao"/> de la configuration XML (et si c'est tout ce qui existe dans la configuration, je vous suggère de supprimer tout le fichier).

Ceci est nécessaire car JpaGebruikerDao est déjà enregistré en tant que bean (Repository) via l'analyse de composant (sous le nom gebruikerDAO).

14
geoand

Supprimez l'annotation @Repository ("gebruikerDAO") de la classe JpaGebruikerDao, car elle est déjà enregistrée.

1
rsaad

Il existe deux solutions possibles pour cette exception . 1- Définissez la classe uniquement dans le fichier XML et utilisez @Qualifier:

public class PlanningController {

@Autowired
@Qualifier("GebruikerDAO")
private GebruikerDAO gebruikerDao;

En XML, définissez un bean pour PlanningController uniquement

2- Ou supprimez les annotations de qualificatif et ajoutez des getters et des setters ou un constructeur dans PlanningController puis, dans le XML, définissez le contexte avec la propriété:

<bean class="[path of PlanningController]">
<property name="gebruikerDao" ref="[GebruikerDAO implementation bean name]"/>

0
user666