我想知道我应该在哪里(或如何)声明我的micronaut项目中的把手的帮助器?
我尝试了以下方法:
public class Application {
public static void main(String[] args) {
Micronaut.run(Application.class);
Handlebars handlebars = new Handlebars();
handlebars.registerHelpers(HelperSource.class);
}
}当然,没有效果。如何在Micronaut应用程序中成功注册Handlebars?
发布于 2018-11-07 23:40:15
在当前的Micronaut 1.0 GA版本中,没有注册Handlebar辅助对象的配置。但是,您可以应用一种简单的解决方法来克服此限制。要使帮助器注册成为可能,您必须访问io.micronaut.views.handlebars.HandlebarsViewsRenderer类及其内部属性handlebars。好消息是这个属性有一个protected作用域-这意味着我们可以在源代码中的同一个包中创建另一个bean,我们可以注入HandlebarsViewsRenderer并访问HandlebarsViewsRenderer.handlebars字段。有了这个字段的访问权,我们就可以执行handlebars.registerHelpers(...)方法了。
您可以简单地执行以下步骤:
1.添加Handlebars.java依赖
compile "com.github.jknack:handlebars:4.1.0"将其添加到编译作用域中很重要,因为运行时作用域不允许访问HandlebarsViewsRenderer.handlebars对象。
2.创建io.micronaut.views.handlebars.HandlebarsCustomConfig类
src/main/java/io/micronaut/views/handlebars/HandlebarsCustomConfig.java
package io.micronaut.views.handlebars;
import javax.inject.Singleton;
import java.util.Date;
@Singleton
public final class HandlebarsCustomConfig {
public HandlebarsCustomConfig(HandlebarsViewsRenderer renderer) {
renderer.handlebars.registerHelpers(new HelperSource());
}
static public class HelperSource {
public static String now() {
return new Date().toString();
}
}
}在这个类中,我创建了一个简单的HelperSource类,它公开了一个名为{{now}}的帮助器。
3.加载HandlebarsCustomConfig bean
package com.github.wololock.micronaut;
import io.micronaut.context.ApplicationContext;
import io.micronaut.runtime.Micronaut;
import io.micronaut.views.handlebars.HandlebarsCustomConfig;
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = Micronaut.run(Application.class);
ctx.getBean(HandlebarsCustomConfig.class);
}
}这一步至关重要。我们需要加载bean,否则Micronaut不会创建它的实例,我们的helpers注册也不会发生。
4.创建视图
src/main/resources/views/home.hbs
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>Now is {{now}}</p>
</body>
</html>5.运行应用程序并查看结果

@Replaces替代方案
您可以使用Micronauts @Replaces注释将HandlebarsViewsRenderer替换为自定义实现。
import io.micronaut.context.annotation.Replaces;
import io.micronaut.core.io.scan.ClassPathResourceLoader;
import io.micronaut.views.ViewsConfiguration;
import javax.inject.Singleton;
import java.util.Date;
@Singleton
@Replaces(HandlebarsViewsRenderer.class)
public final class CustomHandlebarsViewsRenderer extends HandlebarsViewsRenderer {
public CustomHandlebarsViewsRenderer(ViewsConfiguration viewsConfiguration,
ClassPathResourceLoader resourceLoader,
HandlebarsViewsRendererConfiguration handlebarsViewsRendererConfiguration) {
super(viewsConfiguration, resourceLoader, handlebarsViewsRendererConfiguration);
this.handlebars.registerHelpers(new HelperSource());
}
static public class HelperSource {
public static String now() {
return new Date().toString();
}
}
}与以前的解决方案相比,它有几个优势:
io.micronaut.views.handlebars包中创建它。main方法中获取bean即可正确地对其进行初始化。https://stackoverflow.com/questions/53190958
复制相似问题