Search code examples
glassfishejb-3.0startupdozer

Dozer DozerBeanMapper Instantiation Startup EJB App Server Glassfish


Dozer's documentation states that you should only have one instance of DozerBeanMapper running in the app on the server. For initial development I ignored this, now I want to update the app to do this.

How can I instantiate the DozerBeanMapper class when the application starts on glassfish, and how would I access its "map" method in another class once the application has started or been newly deployed?

This is for EJBs so I can't use any servlet to do this.



OK, so I've finally had time to refactor this code. With the pointer from @Mikko Maunu, I am editing my question to provide the code that I have working for me for anyone who might find it useful in the future.

package com.xyz.utilities.singleton;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import org.dozer.DozerBeanMapper;

@Startup
@Singleton
public class DozerInstantiator {

  private DozerBeanMapper mapper = null;

  @PostConstruct
  void init() {
    mapper = new DozerBeanMapper();
  }

  public DozerBeanMapper getMapper() {
    return mapper;
  }

}

And here is a straight forward usecase:

Inject an EJB member variable to your client class:

  @EJB
  DozerInstantiator di;

Within a method somewhere in the client class you can invoke the dozer mapper like so:

Credentials credentials = di.getMapper().map(credentialsDTO, Credentials.class);
// or
Credentials credentials = new Credentials();
di.getMapper().map(credentialsDTO, credentials);

If this is wrong or off base, someone please leave a comment. Until then, this seems to work so I'll use this solution I've developed with Mikko's input.


Solution

  • If you are using GlassFish 3.x, then you can use EJB 3.1 Singleton Session Bean:

    @Startup //initialization in application startup
    @Singleton //only one instance 
    public class DozerInitializer {
        private String status;
    
        @PostConstruct //executed once and only once when sole instance is created
        void init {
            //do steps needed to instantiate DozerBeanMapper
            //here
        }
    }