Anoop Halgeri
Anoop Halgeri

Reputation: 660

Spring Bean Extensions

I have a Spring MVC project with a generic application context xml file. This file defines the generic configuration of my applciation such as the base property file for i18n and data source to connect to the database and so on. While i define this context file i also want to define the session factory which will have base configurations such as the data source to use, the second level caching (eh-cache) and so on. But this will not contain the list of entity beans that my application would load. I want to keep the mapping of the entity beans only in separate file and load them based on need.

Is there a possibility to extend the session factory that i had defined in the base file and only add the additional entity beans? I will eventually have several spring configuration files which will load a separate set of entities. can this be achieved?

Upvotes: 0

Views: 627

Answers (1)

Jose Luis Martin
Jose Luis Martin

Reputation: 10709

There are several posibilities.

  • You can use PropertyPlaceHolderConfigurer to externalize the entity list to a property file. (You can use SPEL in the property file).

  • You can use an abstract bean definition and use it as parent in other sessionFactory beans, then you can import thems based on a Enviroment PropertySource.

Note that Hibernate SessionFactory is inmutable after building it and SessionFactoryBean build SessionFactory in afterPropertiesSet method so the work of setting up the SessionFactoryBean that you want must be done by some BeanFactoryPostProcessor

EDIT

After reading your comment, I think that you could declare a EntityClassHolder bean and use the Autowire collections facility to get all entities in a EntityClassFactoryBean that you can inject in a single SessionFactoryBean. But i don't sure if that is that you want to do:

public class EntityClassHolder {

  List<Class<?>> entityClasses;

  public List<Class<?>> getEntityClasses() {
    return entityClasses;
  }

  public void setEntityClasses(List<Class<?>> entityClasses) {
    this.entityClasses = entityClasses;
  }
}



  public class EntityClassFactoryBean extends AbstractFactoryBean<List<Class<?>>> {

    @Autowired
    List<EntityClassHolder> list; 

    @Override
    public Class<?> getObjectType() {
        return List.class;
    }

    @Override
    protected List<Class<?>> createInstance() throws Exception {
        ArrayList<Class<?>> classList = new ArrayList<Class<?>>();
        for (EntityClassHolder ech : list) {
            classList.addAll(ech.getEntityClasses());
        }

        return classList;
    }
}

Now, if you have several applicatonContext-xxx.xml for example, the SessionFactory will be configured with entity classes definied in EntityClassHolder beans when you load one of them.

Upvotes: 1

Related Questions