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 :

[Transaction][Annotation] Utilisation des annotations Spring [Data]


Sujet :

Spring Java

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2007
    Messages : 51
    Points : 30
    Points
    30
    Par défaut [Transaction][Annotation] Utilisation des annotations Spring
    Bonjour tout le monde,

    J'ai une question concernant les annotations Spring.
    Mon application utilise aujourd'hui spring-config.xml pour déclarer les DAO et les services que je fais injecter dans ma classe Main via cette syntaxe :

    Classe Main :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
         public static Service service;
     
    	public static void main(String[] args) throws Exception {
    		// configuration de l'application
    		ApplicationContext ctx = new ClassPathXmlApplicationContext(
    				"spring-config.xml");
    		// couche service
    		service = (Service) ctx.getBean("service");
                   service.getAllPersonnes();
    Mon problème est que je commence à avoir un bon nombre de DAO et de services. Je voulais passer aux annotations pour éviter d'augmenter la taille du fichier spring-config.xml en y ajoutant chaque fois les nouveaux DAO et les nouveaux services.

    Je me suis documenter aux sujet des annotations grace au post de Tommy. Mais je bloque au niveau de l'injection des services dans ma classe Main.
    Je ne sais pas quel annotation utiliser et comment faire pour récuperer le service
    Je ne sais pas aussi qu'est-ce qu'il faut changer dans mon fichier de configuration pour que ca marche !

    voici mon code :

    /*************** DAO **********************/
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    @Repository
    @Transactional
    public class DaoImpl implements Dao {
     
    	@PersistenceContext
    	private EntityManager em;
    ...
    }

    /*************** SERVICE **********************/
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    @Service
    public class ServiceImpl implements IService {
     
     
    	@Autowired
           //Injection du DAO
    	private Dao dao;
     
    	public void setDao(Dao dao) {
    		this.dao = dao;
    	}
    ...
    }
    /*************** MAIN**********************/
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
         public static Service service;
     
    	public static void main(String[] args) throws Exception {
     
                 // Normalement il ne faut plus faire ceci mais une annotation ???
     
    		ApplicationContext ctx = new ClassPathXmlApplicationContext(
    				"spring-config.xml");
    		// Injection du service
    		service = (Service) ctx.getBean("service");
     
                   service.getAllPersonnes();
    /*************** Spring-config.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
     
         <?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:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
     
    	<tx:annotation-driven />
    	<context:annotation-config/>
        <context:component-scan base-package="dao" />
        <context:component-scan base-package="service" /> 
    	<aop:aspectj-autoproxy />
     
    	<!-- couches applicatives 
    	<bean id="dao" class="dao.DaoImpl" />
    	<bean id="service" class="service.ServiceImpl">
    		<property name="dao" ref="dao" />
    	</bean>
    -->
    	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="jpaVendorAdapter">
    			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">			 
     
    				<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
    				<property name="generateDdl" value="true" />
    			</bean>
    		</property>
    		<property name="jpaProperties">
                     <props>
                         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                         <prop key="hibernate.hbm2ddl.auto">create</prop><!--  validate | update | create | create-drop-->
                     </props>
            </property>
    		<property name="loadTimeWeaver">
    			<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    		</property>
    	</bean>
     
    	<!-- la source de donnéees DBCP -->
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
    		<property name="url" value="jdbc:mysql://10.122.204.52/jpa" />
    		<property name="username" value="root" />
    		<property name="password" value="root" />
    	</bean>
     
    	<!-- le gestionnaire de transactions-->
    	<tx:annotation-driven transaction-manager="txManager" />
    	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    	</bean>
     
    	<!-- traduction des exceptions -->
    	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
     
    	<!-- persistence -->
    	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
     
    </beans>
    Merci beaucoup d'avance pour votre aide.

  2. #2
    Expert éminent
    Avatar de djo.mos
    Profil pro
    Inscrit en
    Octobre 2004
    Messages
    4 666
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2004
    Messages : 4 666
    Points : 7 679
    Points
    7 679
    Par défaut
    Salut,
    Je me trompe peut être, mais je ne crois pas que tu peux répéter l'élement <context:component-scan> plus d'une fois.
    Essaies donc de le mettre unen seule fois avec le nom du package parent du dao et du service (ajoutes en un dans ton cas).


    De même, t'as répété l'élement <tx:annotation-driven> 2 fois. Vires le premier.

    Et t'as pas besoin de déclarer le 2 derniers beans :

    Code xml : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    <!-- traduction des exceptions -->
    	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
     
    	<!-- persistence -->
    	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    Sinon, c'est quoi le problème au juste ? tu veux pas avoir à récupérer tous les beans à la main depuis le main() ? Dans ce cas, déclares un autre bean où tu injectes les autrres beans et récupères juste celui-ci ...

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2007
    Messages : 51
    Points : 30
    Points
    30
    Par défaut Injection d'un bean Service dans un main
    Salut,

    Merci de m'avoir répondu.

    Je t'explique mon problème :

    Je développe une application avec plusieurs DAO et plusieurs Services. Donc je passais par le fichier spring-config.xml pour les déclarer tous afin de me les faire injecter dans ma classe main.
    Afin d'éviter de me taper toutes les déclarations dans mon spring-config.xml, j'ai pensé passer par les annotation de spring. Donc, j'ai rajouté les bonnes annotations dans mon DAO puis dans ma classe service, comme je l'ai indiqué dans mon ancien post, mais je ne sais pas quelles annotations utiliser pour injecter mes services dans ma classe main.

    Le code ci-dessous correspond à mon ancienne classe main qui se basait sur le fichier de conf pour injecter un service.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     
    // configuration de l'application
    		ApplicationContext ctx = new ClassPathXmlApplicationContext(
    				"spring-config.xml");
    		// couche service
    		service = (Service) ctx.getBean("service");
                   service.getAllPersonnes();
    Mais logiquement, avec les annotation je n'aurais plus à faire ça ?
    De toutes les manières, ce bout de code ne marche plus !
    Je voulais savoir par quoi le remplacer pour le faire injecter mon service ServiceImpl ?

    Merci beaucoup pour ta réponse.

  4. #4
    Expert éminent
    Avatar de djo.mos
    Profil pro
    Inscrit en
    Octobre 2004
    Messages
    4 666
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2004
    Messages : 4 666
    Points : 7 679
    Points
    7 679
    Par défaut
    Citation Envoyé par hkefi Voir le message
    Mais logiquement, avec les annotation je n'aurais plus à faire ça ?
    De toutes les manières, ce bout de code ne marche plus !
    Je voulais savoir par quoi le remplacer pour le faire injecter mon service ServiceImpl ?

    Merci beaucoup pour ta réponse.
    Si si, il te faut toujours faire ça même avec les annotations, du moment que t'es dans une application Java SE. Mais tu n'aurais plus à déclarer les beans dans le XML.

    Et ça marche pas car tu passes un mauvais identifiant ici :

    service = (Service) ctx.getBean("service")
    Quand t'as déclaré ton service comme étant bean Spring (avec @Service), tu n'as pas spécifié d'identifiant. Spring lui assigne don le nom court de la classe avec la première lettre en minuscules "serviceImpl"

    Tu peux spécifier un id avec les annotations :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    @Service("service")
    public class ServiceImpl implements IService {

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2007
    Messages : 51
    Points : 30
    Points
    30
    Par défaut Merciiiii
    Salut Djo.mos,

    Merci infiniment pour ta réponse. Ca marche parfaitement bien.
    Je pensais qu'avec les annotation, il fallait enlever la ligne de récupération du contexte de l'application.
    Mais je voulais rebondir sur ta remarque
    Si si, il te faut toujours faire ça même avec les annotations, du moment que t'es dans une application Java SE.
    En fait ma classe Main sert uniquement pour tester mes services mais je compte bien utiliser mes services en environnement J2EE. donc quand je vais passer par une servlet, il faudra faire autrement ?
    D'ailleurs je voulais savoir si ma configuration de spring manquait quelque chose pour pouvoir l'utiliser dans un tomcat ?

    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
     
    <?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:context="http://www.springframework.org/schema/context"
    	xmlns:jee="http://www.springframework.org/schema/jee"
    	xmlns:tx="http://www.springframework.org/schema/tx"
    	xsi:schemaLocation="
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
     
    	<context:annotation-config />
    	<context:component-scan base-package="dao" />
    	<context:component-scan base-package="service" />
     
    	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="jpaVendorAdapter">
    			<bean
    				class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    				<property name="showSql" value="true" />
    				<property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
    				<property name="generateDdl" value="true" />
    			</bean>
    		</property>
    		<property name="jpaProperties">
    			<props>
    				<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop>
    				<prop key="hibernate.hbm2ddl.auto">create</prop><!--  validate | update | create | create-drop-->
    			</props>
    		</property>
    		<property name="loadTimeWeaver">
    			<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    		</property>
    	</bean>
     
    	<!-- la source de donnéees DBCP -->
    	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
    		<property name="url" value="jdbc:mysql://localhost/jpa" />
    		<property name="username" value="root" />
    		<property name="password" value="root" />
    	</bean>
     
    	<!-- le gestionnaire de transactions -->
    	<tx:annotation-driven transaction-manager="txManager" />
    	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    	</bean>
    </beans>
    Encore 1000 Merci.

  6. #6
    Expert éminent
    Avatar de djo.mos
    Profil pro
    Inscrit en
    Octobre 2004
    Messages
    4 666
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2004
    Messages : 4 666
    Points : 7 679
    Points
    7 679
    Par défaut
    Citation Envoyé par hkefi Voir le message

    En fait ma classe Main sert uniquement pour tester mes services mais je compte bien utiliser mes services en environnement J2EE. donc quand je vais passer par une servlet, il faudra faire autrement ?
    D'ailleurs je voulais savoir si ma configuration de spring manquait quelque chose pour pouvoir l'utiliser dans un tomcat ?
    Oui, c'est un peu différent dans un environnment Java EE car celui-ci est managé (c'est le conteneur qui gère le cycle de vie des composants), à l'inverse d'une application Java SE ou tu diriges tout.

    Généralement, dans une application web (dans Tomcat entre autres), tu déclares un listener de Spring qui se charge de créer automatiquement l'application context au démarrage et le détruit à l'arrêt http://java.developpez.com/faq/sprin...ebconfigspring

    Donc, c'est plus toi qui crée l'application context.
    Dans le cas des servlets, pas de bol, tu devrais récupérer les beans à la main, pas comme tu le fais maintenant, mais un truc du genre :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    WebApplicationContext ac = WebApplicationContextUtils
    							.getWebApplicationContext(httpRequest
    									.getSession(false/false).getServletContext());
    Par contre, si tu utilises un framework web, genre Wicket, Stripes, Tapestry, Spring MVC, Struts, JSF, etc., ce serait beaucoup plus simple et propre, car ces frameworks proposent une intégration avec Spring (ou l'autre chemin, comme pour JSF où c'est Spring qui le supporte)

    Exemple avec JSF : http://java.developpez.com/faq/sprin...jsfintegration ou http://blog.developpez.com/djo-mos?t...ne_application

  7. #7
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Janvier 2007
    Messages : 51
    Points : 30
    Points
    30
    Par défaut Merci beaucoup pour ta réponse
    Merci beaucoup pour ta réponse.
    Ca marche parfaitement.
    Je vais fermer ce post et je vais ouvrir un autre, j'ai un problème relatif à la session hibernate dans Spring.

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

Discussions similaires

  1. utilisation des annotations sous netbeans
    Par rota90 dans le forum NetBeans Platform
    Réponses: 0
    Dernier message: 19/03/2014, 15h28
  2. [MVC] SpringMvc 3.0 : possibilité d'utiliser xml au lieu des annotations ?
    Par kabbali999 dans le forum Spring Web
    Réponses: 1
    Dernier message: 20/01/2011, 18h32
  3. Réponses: 2
    Dernier message: 28/10/2009, 09h57
  4. Réponses: 3
    Dernier message: 29/01/2008, 08h48
  5. [RCP] utilisation des tables spring RCP
    Par sprite28121982 dans le forum Spring
    Réponses: 3
    Dernier message: 26/12/2006, 21h02

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