如何直接从视图调用服务?我正在尝试${my.domain.service.method}
,但它抱怨找不到该属性。
不,我不想使用控制器,因为视图是模板。
最好使用标记库,因为通过类加载器直接在视图中创建服务实例将不会自动装配可能存在于您尝试使用的服务中的其他服务声明。
使用标签库,您将自动连接这些服务。
在您的 gsp 视图中<g:customTag param1="$modelObjec" param2="someString" />
在您的 taglib 文件夹 ( yourApp/grails-app/taglib/com/something/MyAppTagLib
) 中:
package com.something
class MyAppTagLib {
def myService // This will be auto-wired
def customTag = { attribs ->
def modelObj = attribs['param1']
def someString = attribs['param2']
// Do something with the params
myService.method()
out << "I just used method of MyService class"
}
}
您的我的服务:
package com.something
class MyService {
def anotherService // This will be auto-wired
def method() {
anotherService.anotherMethod()
}
}
试试这个 - 很有帮助
%{--Use BlogService--}%
<g:set var="blog" bean="blogService"/>
<ul>
<g:each in="${blog.allTitles()}" var="title">
<li>${title}</li>
</g:each>
</ul>
这也不是推荐的东西,你总是可以使用 taglib
我认为最好的方法是:
<%
def myService = grailsApplication.mainContext.getBean("myService");
%>
这样,您就可以在不丢失自动装配服务的情况下获得服务实例。
<%@ page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
然后你可以${myService.method()}
在你的 gsp 视图中调用
请注意,从视图调用事务服务方法会损害性能。最好将所有事务服务方法调用移动到控制器(如果可以的话)