Injecting spring beans into a groovy script - spring

Is it possible to inject Spring beans into a groovy script?
I want to be able to use service/repository methods from a spring application in groovy scripts

Is it possible to inject Spring beans into a groovy script?
Yes. You can "inject" any object you like, Spring Bean or otherwise, into a Groovy script. It isn't injection in the sense that Spring does dependency injection, but you can get the variable into the script easily by putting it in a shell binding:
def binding = new Binding()
// instead of "new"-ing up an instance, you could do this
// from wherever in your Spring app that you have injected
// the SomeHelper bean
binding.someHelper = new SomeHelper()
// script could be loaded from a file, or hardcoded,
// loaded from a db, etc...
def groovyScript = '''
println someHelper.magicNumber
'''
def shell = new GroovyShell(binding)
shell.evaluate(groovyScript)

Related

Run script #Bean classes in kotlin spring application

So I have a spring application on kotlin and to test a particular class I want to write up a script but the problem is all these classes are #Component and it'll be pain to intialize each class using new . Is there any way I can utilise the Beans configured in my main function.
I've tried setting up applciation context which returns null, tried lot of things from internet but no luck.
So, after some searching. I found a way.
in the main function where the Spring application starts.
val context = runApplication<App>(*args)
val crawler = context.getBean(MyClass::class.java)
ref: Accessing Spring managed beans outside spring managed classes in kotlin

Yaml type-safe configuration in Spring using Kotlin Functional Style

I'm trying to follow the demo https://github.com/sdeleuze/spring-kotlin-functional to create a new Spring Boot application using the annotation-free new approach, released in Spring Boot 2. My problem is how to continue to use Yaml files to configure my application, without using annotations? I would guess it would be something inside the Beans configuration but I dont find any documentation on that subject. Thanx
The beans dsl has an env property that you can use to retrieve any environment property defined in yaml, properties files or command line parameters:
fun beans() = beans {
bean<SomeBeanThatNeedsConfig> {
SomeBeanThatNeedsConfig(env.getProperty("config.value"))
}
}

How to access the ServletContext in resources.groovy for Grails 3?

I need to define several beans for spring and to configure the beans I need access to the ServletContext. Previously in Grails 2.x we had code like
beans = {
...
dataProvider(DataProvider) {
def context = ServletContextHolder.getServletContext()
// use context to configure this bean
}
...
}
However in grails 3.x (3.1.10 to be specific), the context variable is always null. If there is another place other than the resources.groovy file that will accomplish this, then that's fine too.
I would use
def context = application.mainContext.servletContext

How to initialize Application Context in Spring Framework 4

I have a project based on Spring Framework 4 and its subproject - Spring Data Solr.
All examples I had a chance to see explain how to organize your project - from base entity ( pojo's ) classes till spring specific classes such as repositories and service. When it came to test functionality all examples show a test with private field ( spring bean ) which usually becomes initialized with the help of annotation
#ContextConfiguration(classes = some-spring-data-main-class.class, loader = SpringApplicationContextLoader.class)
Then it is possible to call for it's bean's methods in #Test methods.
But, when it comes to init bean in a project - how to make it with Spring 4, which is completely XMLless ( I mean, I do not have an applicationContext xml file ).
P.S. in Spring 3 we usually wrote smth like:
ApplicationContext context = new ClasspathApplicationContext("applicationContext.xml")
Is it reasonable to expect smth similar to this of Spring 4 introduces absolutely new concepts of application initialization? What should we write now to init app's first bean?
I got it !
In Spring 4 now we have to write:
ApplicationContext context = new AnnotationConfigApplicationContext(<out-main-config-class>.class);
and then call for beans and its methods.

dynamically declare beans at runtime in Spring

I am wondering if the following is possible. For testing purposes, I wish for different mock classes to be declared in the application context for different tests. These are acceptance tests, using the Jersey REST client. Is there a way to dynamically declare a bean at runtime? Does Spring have an API to allow changes to the application context after the context has been loaded?
The common way to have different beans in the application context is using profiles. You can read about profiles in the following spring source posts:
http://blog.springsource.org/2011/02/14/spring-3-1-m1-introducing-profile
http://blog.springsource.org/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles/
About your first question, you can declare beans at runtime via BeanDefinitionRegistry.registerBeanDefinition() method, for example:
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SomeClass.class);
builder.addPropertyReference("propertyName", "someBean"); // add dependency to other bean
builder.addPropertyValue("propertyName", someValue); // set property value
DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
factory.registerBeanDefinition("beanName", builder.getBeanDefinition());
Is possible also to register a singleton bean instance (already configured) with
context.getBeanFactory().registerSingleton(beanName, singletonObject)
Finally, Spring don't provides a clear way to change a bean after refreshing the context, but the most common approachs are:
close and refresh again (obiously)
Use a proxy and swap the targetSource at runtime: see Replace spring bean in one context with mock version from another context (for an example).

Resources