4.2 The Application Class

Every new Grails application features an Application class within the grails-app/init directory.

The Application class subclasses the GrailsAutoConfiguration class and features a static void main method, meaning it can be run as a regular application.

4.2.1 Executing the Application Class

There are several ways to execute the Application class, if you are using an IDE then you can simply right click on the class and run it directly from your IDE which will start your Grails application.

This is also useful for debugging since you can debug directly from the IDE without having to connect a remote debugger when using the run-app —debug-jvm command from the command line.

You can also package your application into a runnable WAR file, for example:

  1. $ grails package
  2. $ java -jar build/libs/myapp-0.1.war

This is useful if you plan to deploy your application using a container-less approach.

4.2.2 Customizing the Application Class

There are several ways in which you can customize the Application class.

Customizing Scanning

By default Grails will scan all known source directories for controllers, domain class etc., however if there are packages in other JAR files you wish to scan you can do so by overriding the packageNames() method of the Application class:

  1. class Application extends GrailsAutoConfiguration {
  2. @Override
  3. Collection<String> packageNames() {
  4. super.packageNames() + ['my.additional.package']
  5. }
  6. ...
  7. }

Registering Additional Beans

The Application class can also be used as a source for Spring bean definitions, simply define a method annotated with the Bean and the returned object will become a Spring bean. The name of the method is used as the bean name:

  1. class Application extends GrailsAutoConfiguration {
  2. @Bean
  3. MyType myBean() {
  4. return new MyType()
  5. }
  6. ...
  7. }

4.2.3 The Application LifeCycle

The Application class also implements the GrailsApplicationLifeCycle interface which all plugins implement.

This means that the Application class can be used to perform the same functions as a plugin. You can override the regular plugins hooks such as doWithSpring, doWithApplicationContext and so on by overriding the appropriate method:

  1. class Application extends GrailsAutoConfiguration {
  2. @Override
  3. Closure doWithSpring() {
  4. {->
  5. mySpringBean(MyType)
  6. }
  7. }
  8. ...
  9. }