Raible's Wiki

Raible Designs
Wiki Home
News
Recent Changes

AppFuse

Homepage
  - Korean
  - Chinese
  - Italian
  - Japanese

QuickStart Guide
  - Chinese
  - French
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish
  - Japanese

User Guide
  - Korean
  - Chinese

Tutorials
  - Chinese
  - German
  - Italian
  - Korean
  - Portuguese
  - Spanish

FAQ
  - Korean

Latest Downloads

Other Applications

Struts Resume
Security Example
Struts Menu

Set your name in
UserPreferences


Referenced by
Articles
Articles_pt
CreateActions_pt
CreateDAO_pt
SpringControllers_pt




JSPWiki v2.2.33

[RSS]


Hide Menu

CreateManager_pt


This is version 2. It is not the current version, and thus it cannot be edited.
[Back to current version]   [Restore this version]


Part II: Criando novos Managers (gerentes) - Um HowTo para criação de Business Delegates que conversa com as camadas banco de dados (DAOs) e web (Struts Actions or Spring Controllers).
Este tutorial depende da Parte I: Criando novos DAOs e Objetos no AppFuse.

Sobre este Tutorial

Este tutorial mostrará como criar uma classe que delega regras de negócio (e um teste JUnit) para conversar com o DAO que criamos na Parte I.

No contexto do AppFuse, isto é chamado de classe Manager(Gerente). Sua responsabilidade principal é agir como uma ponte entre a camada de persistência(DAO) e a camada web. O padrão Business Delegate da Sun dita que estes objetos são úteis para desacoplar a camada de apresentação da camada de dados (i.e. para aplicações Swing). Gerentes(Managers) devem ser colocados onde lógicas de negócio são necessárias.

Vou dizer a vocês como faço as coisas no Mundo Real em textos como este.

Vamos começar criando novas classes ManagerTest e Manager na arquitetura AppFuse.

Tabela de Conteúdo

  • [1] Criar um novo ManagerTest para rodar testes JUnit no Manager
  • [2] Criar um novo Manager para conversar com o DAO
  • [3] Configurar o Spring para este Manager e as Transações
  • [4] Rodar o ManagerTest

Criar um novo ManagerTest para rodar testes JUnit no Manager [#1]

Na Parte I, criamos o objeto Person e o PersonDao - então vamos continuar a desenvolver esta entidade. Primeiramente, vamos criar o teste JUnit para o PersonManager. Crie a classe PersonManagerTest no diretório test/service/**/service. Queremos testar os mesmos métodos básicos (get, save, remove) que o nosso DAO tem.
Isto pode parecer redundante (o porquê de todos estes testes!), mas estes testes são EXCELENTES para ter depois de 6 meses de estrada.

Esta classe deve estender BaseManagerTestCase, que já existe no pacote service. A classe pai (BaseManagerTestCase) serve para o mesmo propósito da classe BaseDaoTestCase - carregar um arquivo .properties que possui o mesmo nome de sua classe *Test, assim como inicializar o ApplicationContext do Spring.

Usualmente eu copio (open → save as) um teste existente (i.e. UserManagerTest.java) e utilizando ctrl+f para encontrar/substituir [Uu]ser com [Pp]erson, ou qualquer que seja o nome do meu objeto.

O código abaixo é o que precisamos para um teste JUnit básico para nossos Managers. Diferente do DaoTest, este teste utiliza jMock para isolar o Manager de suas dependências e fazer um teste unitário verdadeiro.


package org.appfuse.service;

import java.util.List;
import java.util.ArrayList;
import org.appfuse.dao.PersonDao;
import org.appfuse.model.Person;
import org.appfuse.service.impl.PersonManagerImpl;

import org.jmock.Mock;
import org.springframework.orm.ObjectRetrievalFailureException;

public class PersonManagerTest extends BaseManagerTestCase {
    private final String personId = "1";
    private PersonManager personManager = new PersonManagerImpl();
    private Mock personDao = null;
    private Person person = null;

    protected void setUp() throws Exception{
        super.setUp();
        personDao = new Mock(PersonDao.class);
        personManager.setPersonDao((PersonDaopersonDao.proxy());
    }

    protected void tearDown() {
        super.tearDown();
        personManager = null;
    }
    
}

Now that we have the JUnit framework down for this class, let's add the meat: the test methods to make sure everything works in our Manager. Here's a snippet from the DAO Tutorial tutorial to help you understand what we're about to do.

...we create methods that begin with "test" (all lower case). As long as these methods are public, have a void return type and take no arguments, they will be called by our <junit> task in our Ant build.xml file. Here's some simple tests for testing CRUD. An important thing to remember is that each method (also known as a test), should be autonomous.

Add the following methods to your PersonManagerTest.java file:


    public void testGetPerson() throws Exception {
        person = (Personmgr.getPerson("1");

        assertTrue("person.firstName not null",
                person.getFirstName() != null);
    }

    public void testSavePerson() throws Exception {
        person = (Personmgr.getPerson("1");
        String name = person.getFirstName();
        person.setFirstName("test");

        person = (Personmgr.savePerson(person);
        assertTrue("name updated", person.getFirstName().equals("test"));

        person.setFirstName(name);
        mgr.savePerson(person);
    }

    public void testAddAndRemovePerson() throws Exception {
        person = new Person();
        person = (Personpopulate(person);

        person = (Personmgr.savePerson(person);
        assertTrue(person.getFirstName().equals("Bill"));
        assertTrue(person.getId() != null);

        if (log.isDebugEnabled()) {
            log.debug("removing person, personId: " +
                    person.getId());
        }

        mgr.removePerson(person.getId().toString());

        assertNull(mgr.getPerson(person.getId().toString()));
    }

This class won't compile at this point because we have not created our PersonManager interface.

I think it's funny how I've followed so many patterns to allow extendibility in AppFuse. In reality, on most projects I've been on - I learn so much in a year that I don't want to extend the architecture - I want to rewrite it. Hopefully by keeping AppFuse up to date with my perceived best practices, this won't happen as much. Each year will just be an upgrade to the latest AppFuse, rather than a re-write. ;-)

Create a new Manager to talk to the DAO [#2]

First off, create a PersonManager.java interface in the src/service/**/service directory and specify the basic CRUD methods for any implementation classes. I've eliminated the JavaDocs in the class below for display purposes.

As usual, I usually duplicate (open → save as) an existing file (i.e. UserManager.java).


package org.appfuse.service;

import org.appfuse.model.Person;

import java.util.List;

public interface PersonManager {

    public List getPeople(Person person);

    public Person getPerson(String id);

    public Person savePerson(Object person);

    public void removePerson(String id);
}

Now let's create a PersonManagerImpl class that implements the methods in PersonManager. To do this, create a new class in src/service/**/service and name it PersonManagerImpl.java. It should extend BaseManager and implement PersonManager.


package org.appfuse.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.appfuse.model.Person;
import org.appfuse.dao.PersonDao;

import java.util.List;

/**
 @author mraible
 @version $Revision: $ $Date: May 25, 2004 11:46:54 PM $
 */
public class PersonManagerImpl extends BaseManager implements PersonManager {
    private static Log log = LogFactory.getLog(PersonManagerImpl.class);
    private PersonDao dao;

    public void setPersonDao(PersonDao dao) {
        this.dao = dao;
    }

    public List getPeople(Person person) {
        return dao.getPeople(person);
    }

    public Person getPerson(String id) {
        return dao.getPerson(Long.valueOf(id));
    }

    public Person savePerson(Object person) {
        dao.savePerson(person);
        return (Personperson;
    }

    public void removePerson(String id) {
        dao.removePerson(Long.valueOf(id));
    }
}

One thing to note is the setPersonDao method. This is used by Spring to bind the PersonDao to this Manager. This is configured in the applicationContext-service.xml file. We'll get to configuring that in Step 3[3]. You should be able to compile everything now using "ant compile-service"...

Finally, we need to create the PersonManagerTest.properties file in test/service/**/service so that person = (Person) populate(person); will work in our test.

Duplicating (and renaming) the PersonDaoTest.properties is the easy route. Alternatively, you could set the properties manually.
firstName=Bill
lastName=Joy

Now we need to edit Spring's config file for our services layer so it will know about this new Manager.

Configure Spring for this Manager and Transactions [#3]

To notify Spring of this our PersonManager interface and it's implementation, open the src/service/**/service/applicationContext-service.xml file. In here, you will see an existing configuration for the UserManager. You should be able to copy that and change a few things to get the XML fragment below. Add the following to the bottom of this file.


    <!-- Person Manager -->
    <bean id="personManagerTarget" class="org.appfuse.service.PersonManagerImpl" singleton="false">
        <property name="personDao"><ref bean="personDAO"/></property>
    </bean>
    
    <!-- Transaction declarations for business services.  To apply a generic transaction proxy to
         all managers, you might look into using the BeanNameAutoProxyCreator -->
    <bean id="personManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager"><ref bean="transactionManager"/></property>
        <property name="target"><ref local="personManagerTarget"/></property>
        <property name="transactionAttributeSource"><ref local="defaultTxAttributes"/></property>
    </bean>

Note: I had SAX throw an error because defaultTxAttributes was not defined so I replaced the transactionAttributeSource with this instead, which allowed my unit test to run successfully.


<property name="transactionAttributes">
    <props>
      <prop key="*">PROPAGATION_REQUIRED</prop>
    </props>
</property>

Run the ManagerTest [#4]

Save all your edited files and try running "ant test-service -Dtestcase=PersonManager" one more time.

Yeah Baby, Yeah: BUILD SUCCESSFUL
Total time: 9 seconds


Next Up: Part III: Creating Actions and JSPs - A HowTo for creating Actions and JSPs in the AppFuse architecture.



Go to top   More info...   Attach file...
This particular version was published on 06-Nov-2006 13:52:32 MST by RafaelNami.