javadependency-injectionwildflyejb-3.2

EJB Injection When Beans Share an Interface


I'm working on updating some legacy code for a jboss application and I've run into a bit of a jam. I have two ejb beans, PersonBean and ClientBean. ClientBean is responsible for handling client specific services. ClientBean gets injected with an instance of PersonBean which it uses as a delegate to pass along requests to server side services. The problem I'm running into is that both beans also implement a LoginService interface which also needs to get injected. What I want is for an instance of PersonBean to get injected into ClientBean as the loginService but I'm ending up with ClientBean being injected into itself.

What do I need to do to correctly define this ejb mapping?

ClientServiceProviderBean:

@Stateless(name = "ClientServiceProvider")
@Local({ ClientServiceProvider.class, LoginService.class })
public class ClientServiceProviderBean implements ClientServiceProvider, LoginService
{
    @EJB(name = "personService")
    protected PersonService personService;  

    @EJB(name = "loginService")
    protected LoginService loginService;

    @Override
    public LoginDTO getLoggedInUser()
    {
        LoginDTO loginDTO = loginService.getLoggedInUser();
        return loginDTO;
    }

    @Override
    public Long activateSession(String applicationName, String ipAddress)
    {
        return personService.activateSession(applicationName, ipAddress);
    }    
}

PersonServiceBean:

@Stateless(name = "PersonService")
@Local({ PersonService.class })
@Remote({ RemotePersonService.class })
public class PersonServiceBean implements PersonService, RemotePersonService, LoginService
{
    @Override
    @RolesAllowed({ "authenticated" })
    public Long activateSession(String applicationName, String ipAddress)
    {
        Person p = getCallerAsPerson(entityManager, context.getCallerPrincipal());
        SessionActivity sessionActivity = new SessionActivity(p.getId(), applicationName, true, ipAddress);
        sessionActivity = save(entityManager, sessionActivity);
        return sessionActivity.getId();
    }

    @Override
    @PermitAll
    public LoginDTO getLoggedInUser()
    {
        Principal p = context.getCallerPrincipal();
        if (p != null && !"unauthenticated".equals(p.getName()))
        {
            try
            {
                Person person = getCallerAsPerson(entityManager, p);
                if (person != null)
                {
                    return createLoginDTO(person);
                }
            }
            catch (javax.persistence.NoResultException e)
            {
            }
        }
        return null;
    }
}

Solution

  • If you want to inject PersonServiceBean as a LoginService in ClientServiceProviderBean you should add the LoginService.class in the @Local anotation of PersonServiceBean and remove it from ClientServiceProviderBean.