eclipse-ee4j / krazo

Apache License 2.0
51 stars 19 forks source link

Investigate CDI Model support for view engines #261

Open ivargrimstad opened 3 years ago

chkal commented 3 years ago

My thoughts about this:

In most cases a map-like data structure is used to provide data to the template engine. In many cases it is even a java.util.Map. What we could to is to provide some kind of lazy evaluating map which looks up the bean for all calls to get(String).

Something like:

public class CdiMap implements Map<String, Object> {

  private final BeanManager beanManager;

  public CdiMap( BeanManager beanManager ) {
    this.beanManager = beanManager;
  }

  @Override
  public Object get( Object key ) {

    Set<Bean<?>> beans = beanManager.getBeans( key.toString() );
    if( !beans.isEmpty() ) {
      Bean<?> bean = beans.iterator().next();
      CreationalContext<?> ctx = beanManager.createCreationalContext( bean );
      return beanManager.getReference( bean, bean.getClass(), ctx );
    }
    return null;

  }

  /* ... */

}

However, this only works if the engine allows to pass a map. If it just provides a set(String name, Object obj) like API, this won't be possible. In theory, we could collect ALL @Named beans and pass all of them to the engine, but this could lead to performance issues. We could create some kind of proxy for these beans and obtain them lazily, but this could require some kind of bytecode level proxy.

dmaidaniuk commented 2 years ago

@ivargrimstad, @chkal, I will take a look to this enhancement. Probably, exists some nice way how it could be realized.

chkal commented 2 years ago

@dmaidaniuk Thanks a lot! It would be awesome if we could move this forward.