IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Java Discussion :

Spring @autowired et NullPointerException


Sujet :

Spring Java

  1. #1
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut Spring @autowired et NullPointerException
    Bonjour à tous,

    Je développe une application avec spring, hibernate et Vaadin.
    j'ai un problème avec l'injection de dao dans mes classes d'interface graphique.
    Dans certaines classes l'injection se fait avec réussite tandis que dans d'autres classes la référence dao retourne null ce qui provoque une NullPointerException.

    J'ai beau cherché sur internet et les forum sans trouver aucune solution .

    Voici le fichier de configuration beans.xml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    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
    <context:spring-configured />
    
    <context:component-scan base-package="com.businessdecision.tact.bdtechtest.dao" />
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
    
        <bean id="dataSource" class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
    		<property name="driverClassName">
    			<value>com.mysql.jdbc.Driver</value>
    		</property>
    		<property name="url">
    			<value>jdbc:mysql://localhost:3306/gestionnairedb</value>
    		</property>
    		<property name="username">
    			<value>root</value>
    		</property>
    		<property name="password">
    			<value></value>
    		</property>
    		<property name="suppressClose">
    			<value>true</value>
    		</property>
    	</bean>
    
    <bean id="txDataSource"
    		class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
    		<constructor-arg ref="dataSource" />
    	</bean>
    
    	<!-- Hibernate SessionFactory Definition -->
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
    				<prop key="hibernate.show_sql">true</prop>
    				<prop key="hibernate.hbm2ddl.auto">update</prop>
    			</props>
    		</property>
    		<property name="dataSource">
    			<ref bean="txDataSource" />
    		</property>
    		<property name="packagesToScan">
    			<list>
    			<value>com.businessdecision.tact.bdtechtest.domain</value>	
    			</list>
    		</property>
    	</bean>
    	<!-- Using HibernateTemplate, and shared by all DAO object because it is 
    		thread-safe -->
    	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    		<property name="sessionFactory" ref="sessionFactory" />
    		<property name="fetchSize" value="20" />
    		<property name="allowCreate" value="true" />
    		<property name="alwaysUseNewSession" value="false" />
    	</bean>
    
    
    <!-- Hibernate Transaction Manager Definition -->
    	<bean id="transactionManager"
    		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    	
    	<tx:annotation-driven transaction-manager="transactionManager"
    		proxy-target-class="true" />
    		
    			<!-- le gestionnaire de BLOB / CLOB de chez Spring -->
    	<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" />
    
    Voici un exemple d'exception que je reçois
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    FormGestionProfil.java >> utilisateurDao: null
    java.lang.NullPointerException
    	at com.businessdecision.tact.bdtechtest.ui.FormGestionProfil.buttonClick(FormGestionProfil.java:95)
    La ligne générant l'exception
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    if(utilisateurDao.confirmPWD(npwd, user)){
    et la classe générant l'exception
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    @Configurable(preConstruction=true)
    public class FormGestionProfil extends Form implements ClickListener {
     
     
    	private static final long serialVersionUID = 463035994709151133L;
     
    	@Autowired 
    	UtilisateurDao utilisateurDao;
    merci d'avance pour votre aide.

  2. #2
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 31
    Points : 63
    Points
    63
    Par défaut
    Il faut que ton projet soit compilé avec le AJC (compilateur d'AspectJ)

    Si c'est un projet Maven, tu peux ajouter ça

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    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
     
    ...
    			<plugin>
    				<groupId>org.codehaus.mojo</groupId>
    				<artifactId>aspectj-maven-plugin</artifactId>
    				<version>1.3</version>
    				<executions>
    					<execution>
    						<id>compile</id>
    						<configuration>
    							<source>1.6</source>
    							<target>1.6</target>
    							<encoding>${project.build.sourceEncoding}</encoding>
    							<verbose>false</verbose>
    							<outxml>true</outxml>
    							<aspectLibraries>
    								<aspectLibrary>
    									<groupId>org.springframework</groupId>
    									<artifactId>spring-aspects</artifactId>
    								</aspectLibrary>
    							</aspectLibraries>
    							<weaveDependencies>
    								<weaveDependency>
    									<groupId>org.springframework</groupId>
    									<artifactId>spring-aspects</artifactId>
    								</weaveDependency>
    							</weaveDependencies>
    						</configuration>
    						<goals>
    							<goal>compile</goal>
    						</goals>
    					</execution>
    					<execution>
    						<id>test-compile</id>
    						<configuration>
    							<source>1.6</source>
    							<target>1.6</target>
    							<encoding>${project.build.sourceEncoding}</encoding>
    							<verbose>false</verbose>
    							<aspectLibraries>
    								<aspectLibrary>
    									<groupId>org.springframework</groupId>
    									<artifactId>spring-aspects</artifactId>
    								</aspectLibrary>
    							</aspectLibraries>
    							<weaveDependencies>
    								<weaveDependency>
    									<groupId>org.springframework</groupId>
    									<artifactId>spring-aspects</artifactId>
    								</weaveDependency>
    							</weaveDependencies>
    						</configuration>
    						<goals>
    							<goal>test-compile</goal>
    						</goals>
    					</execution>
    				</executions>
    			</plugin>
    ...

  3. #3
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    Bonjour net merci pour votre réponse,

    Le compilateur AJC est déjà présent dans le pom.xml , l'application fonctionne et je peut accèder à l'interface de login et quelques autre interfaces de gestion, seules 2 ou 3 interfaces qui ne sont pas accessibles à cause de l'erreur NullPointerException générée par l'appel au DAO qui doit être injecté par spring.

    Il y'a quelques modifications que je dois apporter au projet pour ajouter une couche Service, peut être que ça résoudra le problème . Je vous tient au courant si je résout le problème .

    Si vous avez quelques conseils ou explications à propos de l'implémentation de la couche service merci de m'en faire part .

  4. #4
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    même problème avec le service

  5. #5
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    En insérant un System.out.println dans le constructeur du bean, j'ai constaté qu'il est instancié mais il n'est pas injecté, pourtant j'ai mis @Autowired au dessus de la variable . Pourquoi ?

  6. #6
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 31
    Points : 63
    Points
    63
    Par défaut
    Il te manque peut-être ça dans ta config Spring :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <context:annotation-config/>

  7. #7
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    j'ai ajouté la balise annotation-config mais elle n'a pas résolu le problème

    l'erreur générée :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    GRAVE: Servlet.service() for servlet Vaadin Application Servlet threw exception
    java.lang.NullPointerException
    	at com.bd.tct.bdtechtest.services.Impl.AuthentificationServiceImpl.connect(AuthentificationServiceImpl.java:38)
    est causé par la ligne suivante:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    System.out.println("authentificationService: "+authentificationService);
    		Utilisateur user = authentificationService.connect(username,password);
    citué dans cette classe:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    @Configurable
    public class ConnectionWindow extends Window implements LoginListener{
     
    	/**
             * 
             */
    	private static final long serialVersionUID = 2986083238380601224L;
    	Utilisateur Utilisateur;
    	Application app;
    	MyLoginForm loginForm;
     
    	private IAuthentificationService authentificationService;
     
    	static Logger logger = Logger.getLogger(ConnectionWindow.class);
     
     
    	@Autowired
    	public void setAuthentificationService(IAuthentificationService authentificationService){
    		this.authentificationService = authentificationService;
    		System.out.println(">> setAuthentificationService: "+authentificationService);
    	}
    ....
    	@Override
    	public void onLogin(LoginEvent event) {
     
    		// TODO Auto-generated method stub
    		String password = event.getLoginParameter("password");
    		String username = event.getLoginParameter("username");
     
    		Utilisateur user = authentificationService.connect(username,password);
    qui ne génère pas d'output.


    Voici le bean de service authentification injecté dans la classe ConnexionWindow:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
     
    @Service("authentificationService")
    public class AuthentificationServiceImpl implements IAuthentificationService {
     
    	@Autowired
    	IDao utilisateurDao;
     
    	public void setUtilisateurDao(IDao utilisateurDao){
    		this.utilisateurDao = utilisateurDao;
    	}
     
    	public IDao getUtilisateurDaoq(){
    		return utilisateurDao;
    	}
     
    	private AuthentificationServiceImpl(){
    		System.out.println("AuthentificationServiceImpl >> AuthentificationService created");
    		System.out.println("AuthentificationServiceImpl >> "+this.toString());
    		System.out.println("AuthentificationServiceImpl >> Dao: "+utilisateurDao);
     
    	}
    Voici l'output qu'il génère:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    AuthentificationServiceImpl >> AuthentificationService created
    AuthentificationServiceImpl >> com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl@1905742
    AuthentificationServiceImpl >> Dao: null


    Enfin voici le DEBUG par log4J :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    13:25:48,734 DEBUG DefaultListableBeanFactory:217 - Creating shared instance of singleton bean 'authentificationService'
    13:25:48,734 DEBUG DefaultListableBeanFactory:430 - Creating instance of bean 'authentificationService'
    AuthentificationServiceImpl >> AuthentificationService created
    AuthentificationServiceImpl >> com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl@1224b90
    AuthentificationServiceImpl >> Dao: null
    13:25:48,734 DEBUG InjectionMetadata:60 - Found injected element on class [com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl]: AutowiredFieldElement for com.businessdecision.tact.bdtechtest.dao.Utils.IDao com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl.utilisateurDao
    13:25:48,734 DEBUG InjectionMetadata:60 - Found injected element on class [com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl]: AutowiredFieldElement for com.businessdecision.tact.bdtechtest.dao.Utils.IDao com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl.utilisateurDao
    13:25:48,734 DEBUG DefaultListableBeanFactory:504 - Eagerly caching bean 'authentificationService' to allow for resolving potential circular references
    13:25:48,734 DEBUG CachedIntrospectionResults:222 - Getting BeanInfo for class [com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl]
    13:25:48,734 DEBUG CachedIntrospectionResults:238 - Caching PropertyDescriptors for class [com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl]
    13:25:48,734 DEBUG CachedIntrospectionResults:250 - Found bean property 'class' of type [java.lang.Class]
    13:25:48,734 DEBUG CachedIntrospectionResults:250 - Found bean property 'utilisateurDao' of type [com.businessdecision.tact.bdtechtest.dao.Utils.IDao]
    13:25:48,734 DEBUG InjectionMetadata:85 - Processing injected method of bean 'authentificationService': AutowiredFieldElement for com.businessdecision.tact.bdtechtest.dao.Utils.IDao com.businessdecision.tact.bdtechtest.services.Impl.AuthentificationServiceImpl.utilisateurDao
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'utilisateurDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'testDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'technologieDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'reponseDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'questionDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'noteCandidatTestDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'cleDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'candidatDao'
    13:25:48,734 DEBUG AutowiredAnnotationBeanPostProcessor:424 - Autowiring by type from bean name 'authentificationService' to bean named 'utilisateurDao'
    13:25:48,734 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'org.springframework.transaction.config.internalTransactionAdvisor'
    13:25:48,750 DEBUG DefaultListableBeanFactory:458 - Finished creating instance of bean 'authentificationService'
    Je ne trouve encore pas l'erreur . comme vous pouvez voir, les beans sont instanciés mais ne sont pas injectés .
    merci d'avance pour votre aide

  8. #8
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    SVP, Toute aide est appréicée

  9. #9
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 31
    Points : 63
    Points
    63
    Par défaut
    Regarde tes logs, l'injection est faite après l'appel au constructeur.

    Ce qui est juste normal : Spring instancie l'objet (donc appel du constructeur) puis fait l'injection des dépendances.

    Transforme ton faux constructeur en méthode annotée @PostConstruct et tu devrais avoir ce que tu veux.

  10. #10
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    Transforme ton faux constructeur en méthode annotée @PostConstruct et tu devrais avoir ce que tu veux.
    Bonjour,

    Je ne comprend pas très bien la solution proposé .Que veut tu dire par faux constructeur ?

    merci

  11. #11
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 31
    Points : 63
    Points
    63
    Par défaut
    "Faux" car il ne sert à rien.

    Donc je reformule :

    Supprime ton constructeur et remplace le par :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    	@PostConstruct
    	public void debugInjection(){
    		System.out.println("AuthentificationServiceImpl >> AuthentificationService created");
    		System.out.println("AuthentificationServiceImpl >> "+this.toString());
    		System.out.println("AuthentificationServiceImpl >> Dao: "+utilisateurDao);
     
    	}

  12. #12
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    Merci pour l'explication,
    Miracle demi-fait, le problème est résolu pour le service d'Authenfication.


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Configurable
    public class ConnectionWindow extends Window implements LoginListener{
     
    	/**
             * 
             */
    	private static final long serialVersionUID = 2986083238380601224L;
    	Utilisateur Utilisateur;
    	Application app;
    	MyLoginForm loginForm;
     
     
    	@Autowired
    	private IUtilisateurService utilisateurService;

    Mais j'ai toujours le même problème dans d'autres classe comme la gestion de profil qui permet de changer le mot de passe :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    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
     
    @Configurable
    public class FormGestionProfil extends Form implements ClickListener {
     
     
    	private static final long serialVersionUID = 463035994709151133L;
    	private static Logger logger = Logger.getLogger(FormGestionProfil.class);
     
    	private IUtilisateurService utilisateurService;
     
    	Utilisateur user;
     
    	HorizontalLayout hlayout = new HorizontalLayout();
    	VerticalLayout vlayout = new VerticalLayout();
     
    	Application app;
     
     
    	@Required
    	@Autowired
    	public void setUtilisateurService(IUtilisateurService utilisateurService) {
    		logger.debug("injecting instance of utilisateurService through setter "+utilisateurService);
    		this.utilisateurService = utilisateurService;
    	}
     
    	public FormGestionProfil(Application app) {
    		this.app = app;
    		this.user = (Utilisateur)app.getUser();
    		buildComponents();
    		logger.debug("injecting instance of utilisateurService through construction "+utilisateurService);
    	}
     
    	@PostConstruct
    	public void debugInjection(){
    		logger.debug("injected utilisateurService: "+utilisateurService);
    	}
    Le plus douloureux c'est que je ne reçoit pas d'exception pour l'annotation @Required (puisque normalement l'injection n'est pas réalisé) et je ne trouve pas le message de log pour debugInjection qui est annoté @PostConstruct

    le seul output qui est généré est celui généré par le constructeur:
    ui.FormGestionProfil>> 14:32:31,899 DEBUG FormGestionProfil:54 - injecting instance of utilisateurService through construction null

    Pour info, la classe FormGestionProfil est instancié par new() , donc je ne peut pas dire que spring fait l'injection par constructeur .

    Voici les messages de Log générés par le service d'authentification :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
    support.AbstractBeanFactory>> 14:32:28,180 DEBUG DefaultListableBeanFactory:245 - Returning cached instance of singleton bean 'transactionManager'
    support.TransactionSynchronizationManager>> 14:32:28,196 DEBUG TransactionSynchronizationManager:272 - Initializing transaction synchronization
    interceptor.TransactionAspectSupport>> 14:32:28,196 DEBUG TransactionInterceptor:362 - Getting transaction for [com.businessdecision.tact.bdtechtest.dao.Utils.BaseDaoHibernate.findByPropertyValue]
    hibernate3.SessionFactoryUtils>> 14:32:28,274 DEBUG SessionFactoryUtils:322 - Opening Hibernate Session
    hibernate3.SessionFactoryUtils>> 14:32:28,321 DEBUG SessionFactoryUtils:330 - Registering Spring transaction synchronization for new Hibernate Session
    support.TransactionSynchronizationManager>> 14:32:28,321 DEBUG TransactionSynchronizationManager:193 - Bound value [org.springframework.orm.hibernate3.SessionHolder@624a40] for key [org.hibernate.impl.SessionFactoryImpl@1c5b2de] to thread [http-8080-1]
    support.TransactionSynchronizationManager>> 14:32:28,321 DEBUG TransactionSynchronizationManager:140 - Retrieved value [org.springframework.orm.hibernate3.SessionHolder@624a40] for key [org.hibernate.impl.SessionFactoryImpl@1c5b2de] bound to thread [http-8080-1]
    hibernate3.HibernateTemplate>> 14:32:28,321 DEBUG HibernateTemplate:397 - Found thread-bound Session for HibernateTemplate
    support.TransactionSynchronizationManager>> 14:32:28,368 DEBUG TransactionSynchronizationManager:140 - Retrieved value [org.springframework.orm.hibernate3.SessionHolder@624a40] for key [org.hibernate.impl.SessionFactoryImpl@1c5b2de] bound to thread [http-8080-1]
    Hibernate: select this_.id as id0_0_, this_.email as email0_0_, this_.login as login0_0_, this_.mot_de_passe as mot4_0_0_, this_.nom as nom0_0_, this_.prenom as prenom0_0_, this_.salt as salt0_0_, this_.type as type0_0_ from Utilisateur this_ where this_.login=?
    datasource.DataSourceUtils>> 14:32:28,368 DEBUG DataSourceUtils:110 - Fetching JDBC Connection from DataSource
    datasource.DataSourceUtils>> 14:32:28,368 DEBUG DataSourceUtils:114 - Registering transaction synchronization for JDBC Connection
    support.TransactionSynchronizationManager>> 14:32:28,383 DEBUG TransactionSynchronizationManager:193 - Bound value [org.springframework.jdbc.datasource.ConnectionHolder@1b68215] for key [org.springframework.jdbc.datasource.SingleConnectionDataSource@84fa6a] to thread [http-8080-1]
    support.TransactionSynchronizationManager>> 14:32:28,399 DEBUG TransactionSynchronizationManager:140 - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@1b68215] for key [org.springframework.jdbc.datasource.SingleConnectionDataSource@84fa6a] bound to thread [http-8080-1]
    hibernate3.HibernateTemplate>> 14:32:28,414 DEBUG HibernateTemplate:422 - Not closing pre-bound Hibernate Session after HibernateTemplate
    interceptor.TransactionAspectSupport>> 14:32:28,414 DEBUG TransactionInterceptor:391 - Completing transaction for [com.businessdecision.tact.bdtechtest.dao.Utils.BaseDaoHibernate.findByPropertyValue]
    support.AbstractPlatformTransactionManager>> 14:32:28,414 DEBUG HibernateTransactionManager:922 - Triggering beforeCommit synchronization
    hibernate3.SpringSessionSynchronization>> 14:32:28,414 DEBUG SessionFactoryUtils:144 - Flushing Hibernate Session on transaction synchronization
    support.AbstractPlatformTransactionManager>> 14:32:28,430 DEBUG HibernateTransactionManager:935 - Triggering beforeCompletion synchronization
    support.TransactionSynchronizationManager>> 14:32:28,430 DEBUG TransactionSynchronizationManager:243 - Removed value [org.springframework.orm.hibernate3.SessionHolder@624a40] for key [org.hibernate.impl.SessionFactoryImpl@1c5b2de] from thread [http-8080-1]
    support.AbstractPlatformTransactionManager>> 14:32:28,430 DEBUG HibernateTransactionManager:948 - Triggering afterCommit synchronization
    support.AbstractPlatformTransactionManager>> 14:32:28,430 DEBUG HibernateTransactionManager:964 - Triggering afterCompletion synchronization
    hibernate3.SessionFactoryUtils>> 14:32:28,430 DEBUG SessionFactoryUtils:800 - Closing Hibernate Session
    support.TransactionSynchronizationManager>> 14:32:28,430 DEBUG TransactionSynchronizationManager:140 - Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@1b68215] for key [org.springframework.jdbc.datasource.SingleConnectionDataSource@84fa6a] bound to thread [http-8080-1]
    support.TransactionSynchronizationManager>> 14:32:28,430 DEBUG TransactionSynchronizationManager:243 - Removed value [org.springframework.jdbc.datasource.ConnectionHolder@1b68215] for key [org.springframework.jdbc.datasource.SingleConnectionDataSource@84fa6a] from thread [http-8080-1]
    support.TransactionSynchronizationManager>> 14:32:28,430 DEBUG TransactionSynchronizationManager:331 - Clearing transaction synchronization
    ui.FormGestionProfil>> 14:32:31,899 DEBUG FormGestionProfil:54 - injecting instance of utilisateurService through construction null
    Il n'y a pas de log pour le service de gestion de profil car le service n'est pas injecté

  13. #13
    Membre du Club
    Homme Profil pro
    Développeur Java
    Inscrit en
    Mai 2012
    Messages
    31
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2012
    Messages : 31
    Points : 63
    Points
    63
    Par défaut
    Si tu veux que l'injection ait lieu avant l'appel au constructeur dans ce cas tu dois annoter ta classe avec :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @Configurable(preConstruction = true)
    Ne fais pas de confusion entre @Configurable @Service:
    • Configurable : c'est pour appliquer l'injection de dépendances aux instances dont le cycle de vie n'est pas géré par Spring (objets instanciés par ton code, comme les composants Vaadin)
    • Service : c'est pour des beans Spring de première catégorie (comme @Component ou @Repository)


    Et puis dans ton fichier de config essaie de remplacer ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    <context:spring-configured />
     
    <context:component-scan base-package="com.businessdecision.tact.bdtechtest.dao" />
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
    <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
    par ça :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    <context:spring-configured />
    <context:component-scan base-package="com.businessdecision.tact" />
    Et il faut aussi que ton la compilation aspectj soit bien réglée. Mais je t'ai déjà donné un exemple dans une autre réponse.

  14. #14
    Membre habitué
    Homme Profil pro
    Développeur Java
    Inscrit en
    Novembre 2008
    Messages
    88
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Novembre 2008
    Messages : 88
    Points : 154
    Points
    154
    Par défaut
    Merci à tous pour votre aide, Problème résolu et tous va bien

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Framework] Maven+Spring : pb avec @Autowired
    Par zev dans le forum Spring
    Réponses: 2
    Dernier message: 02/10/2009, 21h43
  2. [Framework] Injection spring par autowired en cascade
    Par _Moa_ dans le forum Spring
    Réponses: 1
    Dernier message: 11/08/2009, 16h31
  3. [Framework] Spring et autowiring
    Par PomCompot dans le forum Spring
    Réponses: 5
    Dernier message: 20/07/2009, 14h58
  4. [Integration] Spring et Jmock : injecter un mock dans un @autowired
    Par elix63 dans le forum Spring
    Réponses: 1
    Dernier message: 08/07/2009, 08h54
  5. NullPointerException en spring.
    Par balteo dans le forum Spring
    Réponses: 12
    Dernier message: 27/02/2009, 11h58

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo