我有一个vraptor4项目,我想使用apache velocity作为模板引擎。
所以我把br.com.caelum.vraptor.view.DefaultPathResolver专门化为
@Specializes
public class VelocityPathResolver extends DefaultPathResolver {
@Inject
protected VelocityPathResolver(FormatResolver resolver) {
super(resolver);
}
protected String getPrefix() {
return "/WEB-INF/vm/";
}
protected String getExtension() {
return "vm";
}
}这很好,但我不能在模板中包含@Named组件。
拥有
@SessionScoped
@Named("mycmp")
public class MyComponent implements Serializable {
private static final long serialVersionUID = 1L;
private String name = "My Component";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}在我的速度模板(.vm)中,我不能将它称为.vm,但是如果我使用.jsp,它工作得很好。
为了解决这个问题,我将br.com.caelum.vraptor.core.DefaultResult专门化为
@Specializes
public class VelocityResult extends DefaultResult {
private final MyComponent mycmp;
@Inject
public VelocityResult(HttpServletRequest request, Container container, ExceptionMapper exceptions, TypeNameExtractor extractor,
Messages messages, MyComponent mycmp) {
super(request, container, exceptions, extractor, messages);
this.mycmp = mycmp;
}
@PostConstruct
public void init() {
include("mycmp", mycmp);
}
}是否有更好的方法在速度模板中包含@Named组件?
发布于 2015-01-20 11:53:17
看起来CDI的@Named不适用于速度模板,但是您可以实现一个Interceptor来完成这一工作。一个例子是:
@Intercepts
public class IncluderInterceptor {
@Inject private MyComponent mycmp;
@AfterCall public void after() {
result.include("mycmp", mycmp);
// any other bean you want to
}
}在一个更灵活的解决方案中,您可以创建一个注释并使用它来定义应该包含哪个bean .就像这样:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Included {
}这样您就可以在您的课堂上添加@Included:
@Included public class MyComponent { ... },只需在IncluderInterceptor上添加接受方法
@Intercepts
public class IncluderInterceptor {
@Inject @Any Instance<Object> allBeans;
@AfterCall public void after() {
// foreach allBeans, if has @Included, so
// include bean.getClass().getSimpleName()
// with first letter lower case, or something
}
}当然,如果您只包含几个bean,那么第一个解决方案就应该是first。诚挚的问候
https://stackoverflow.com/questions/28024572
复制相似问题