////
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
////

Grails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.


==== Hooking into the Grails Spring configuration


The recommended way to register beans from a plugin is to override the `beanRegistrar` method from the link:{api}grails/plugins/Plugin.html[Plugin] class and return a Spring Framework {springapi}org/springframework/beans/factory/BeanRegistrar.html[BeanRegistrar]. `BeanRegistrar` is a functional interface, so a closure coerced with `as BeanRegistrar` is all that is required — no separate class:

[source,groovy]
----
import org.springframework.beans.factory.BeanRegistrar
import org.springframework.beans.factory.BeanRegistry
import org.springframework.core.env.Environment
import org.springframework.web.servlet.i18n.CookieLocaleResolver
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
import org.springframework.context.support.ReloadableResourceBundleMessageSource
import grails.plugins.Plugin

class I18nGrailsPlugin extends Plugin {

    def version = "0.1"

    @Override
    BeanRegistrar beanRegistrar() {
        { BeanRegistry registry, Environment environment ->
            registry.registerBean('messageSource', ReloadableResourceBundleMessageSource) { spec ->
                spec.supplier { context ->
                    new ReloadableResourceBundleMessageSource(basename: 'WEB-INF/grails-app/i18n/messages')
                }
            }
            registry.registerBean('localeChangeInterceptor', LocaleChangeInterceptor) { spec ->
                spec.supplier { context ->
                    new LocaleChangeInterceptor(paramName: 'lang')
                }
            }
            registry.registerBean('localeResolver', CookieLocaleResolver)
        } as BeanRegistrar
    }
}
----

For more involved or reusable registration you can instead implement `BeanRegistrar` as its own class and return an instance of it from `beanRegistrar()`.

Plugin beans are registered before Spring Boot processes its auto-configurations, so a bean registered here takes precedence over any Spring Boot default guarded by `@ConditionalOnMissingBean` — there is no need to override or remove Boot's beans afterwards.

Alternatively, plugins may override the `doWithSpring` method and return a closure that defines beans using the link:spring.html#theBeanBuilderDSLExplained[Spring Bean Builder] syntax:

[source,groovy]
----
import org.springframework.web.servlet.i18n.CookieLocaleResolver
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
import org.springframework.context.support.ReloadableResourceBundleMessageSource
import grails.plugins.*

class I18nGrailsPlugin extends Plugin {

    def version = "0.1"

    Closure doWithSpring() {{->
        messageSource(ReloadableResourceBundleMessageSource) {
            basename = "WEB-INF/grails-app/i18n/messages"
        }
        localeChangeInterceptor(LocaleChangeInterceptor) {
            paramName = "lang"
        }
        localeResolver(CookieLocaleResolver)
    }}
}
----

NOTE: `doWithSpring` is deprecated as of Grails 8 in favour of `beanRegistrar`. It continues to work — the beans it defines register at the same early point in the lifecycle — but new code should prefer the `BeanRegistrar` API.

Alternatively, you can override the `doWithSpring(BeanBuilder)` method and register beans directly against the supplied `BeanBuilder` instead of returning a closure. This avoids the closure indirection and is the recommended form for statically compiled plugins:

[source,groovy]
----
import org.springframework.web.servlet.i18n.CookieLocaleResolver
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor
import org.springframework.context.support.ReloadableResourceBundleMessageSource
import grails.plugins.*
import grails.spring.BeanBuilder

class I18nGrailsPlugin extends Plugin {

    def version = "0.1"

    @Override
    void doWithSpring(BeanBuilder beans) {
        beans.messageSource(ReloadableResourceBundleMessageSource) {
            basename = "WEB-INF/grails-app/i18n/messages"
        }
        beans.localeChangeInterceptor(LocaleChangeInterceptor) {
            paramName = "lang"
        }
        beans.localeResolver(CookieLocaleResolver)
    }
}
----

A plugin may override either `doWithSpring()` or `doWithSpring(BeanBuilder)`, but not both. The closure-returning `doWithSpring()` remains fully supported for backwards compatibility. Defining both forms in the same plugin is an error: the plugin will fail to load with an exception, since the two forms are alternatives and defining both indicates an incomplete migration between them. Consolidate the bean definitions into a single form.


==== Customizing the Servlet Environment


In previous versions of Grails it was possible to dynamically modify the generated `web.xml`. From Grails 3.x+ there is no `web.xml` file and it is not possible to programmatically modify the `web.xml` file anymore.

However, it is possible to perform the most commons tasks of modifying the Servlet environment in Grails 3.x and above.


==== Adding New Servlets


If you want to add a new Servlet instance the simplest way is simply to define a new Spring bean in the `doWithSpring` method:

[source,groovy]
----
Closure doWithSpring() {{->
  myServlet(MyServlet)
}}
----

If you need to customize the servlet you can use Spring Boot's {springbootapi}org/springframework/boot/web/servlet/ServletRegistrationBean.html[ServletRegistrationBean]:

[source,groovy]
----
Closure doWithSpring() {{->
  myServlet(ServletRegistrationBean, new MyServlet(), "/myServlet/*") {
    loadOnStartup = 2
  }
}}
----


==== Adding New Servlet Filters


Just like Servlets, the simplest way to configure a new filter is to simply define a Spring bean:

[source,groovy]
----
Closure doWithSpring() {{->
  myFilter(MyFilter)
}}
----

However, if you want to control the order of filter registrations you will need to use Spring Boot's {springbootapi}org/springframework/boot/web/servlet/FilterRegistrationBean.html[FilterRegistrationBean]:

[source,groovy]
----
myFilter(FilterRegistrationBean) {
    filter = bean(MyFilter)
    urlPatterns = ['/*']
    order = Ordered.HIGHEST_PRECEDENCE
}
----

NOTE: Grails' internal registered filters (`GrailsWebRequestFilter`, `HiddenHttpMethodFilter` etc.) are defined by incrementing `HIGHEST_PRECEDENCE` by 10 thus allowing several filters to be inserted before or between Grails' filters.


==== Doing Post Initialisation Configuration


Sometimes it is useful to be able do some runtime configuration after the Spring {springapi}org/springframework/context/ApplicationContext.html[ApplicationContext] has been built. In this case you can define a `doWithApplicationContext` closure property.

[source,groovy]
----
class SimplePlugin extends Plugin{

    def name = "simple"
    def version = "1.1"

    @Override
    void doWithApplicationContext() {
        def sessionFactory = applicationContext.sessionFactory
        // do something here with session factory
    }
}
----
