Why not to use services in views directly:
Reason 1: Generally we don't prefer to use the services in grails view as they decrease the performance of application if they are transactional in nature.But we can use them in view in non transactional manner.
Reason2 : If we use services directly in view, then class loader will load that service only by autowiring but not the other services which are referenced in that service.
If services are transactional in nature then either we have to use taglibs in order to use the methods of service or make a controller call to invoke the service method.
How to use in view if necessary:
Way 1 :
<g:set var="user" bean="userService"/>
We can access any service or Spring managed bean in application with the help of this bean attribute in g:set tag of grails.
Way 2:
<%
def myService = grailsApplication.mainContext.getBean("myService");
%>
Using this syntax we can get the reference of the service bean from the Application Container used by the framework.
Way 3:
<%@ page import="com.myproject.MyService" %>
<%
def myService = grailsApplication.classLoader.loadClass('com.myproject.MyService').newInstance()
%>
It will give you new instance of service and completely lost all the autowired things.
Note : Best approach is access the service methods using taglibs.
THANKS
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shiv Kumar
Shiv is an experienced Java Developer with a strong background in multiple technologies. He specializes in defining system architectures to ensure reliable and resilient solutions. He possesses a comprehensive understanding of the latest technologies and has hands-on experience in Core Java, Spring Boot, Hibernate, Apache Kafka messaging queue, Redis, as well as relational databases like MySQL and PostgreSQL, and non-relational databases like MongoDB. He excels in API implementations, Microservices, Web Services development, testing, and deployments. Shiv actively contributes to code enhancements and consistently delivers valuable contributions to various client projects, including Fabtrack, Pando, Pandojo, Digikam, WhatsApp Integration, Croniz, Punchin Application, Script TV, Bhaasha, and more. He demonstrates strong analytical skills and a creative mindset. In addition, he has a passion for reading books and exploring new technologies and innovations.