DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Consumer-Driven Contract Testing With Spring Cloud Contract
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services

Trending

  • How to Submit a Post to DZone
  • Enforcing Architecture With ArchUnit in Java
  • Chat With Your Knowledge Base: A Hands-On Java and LangChain4j Guide
  • GitHub Copilot's New AI Coding Agent Saves Developers Time – And Requires Their Oversight
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring 4 with Groovy

Spring 4 with Groovy

By 
Felipe Gutierrez user avatar
Felipe Gutierrez
·
Dec. 26, 13 · Interview
Likes (4)
Comment
Save
Tweet
Share
27.5K Views

Join the DZone community and get the full member experience.

Join For Free

 Finally the wait is over, Spring 4 is here and one of the best features is that now has a fully support for Groovy. The Spring team did a fantastic job bringing the same concept from Grails into the Spring Framework.

In the past if you needed to incorporate Spring in your Groovy Applications or Scripts , normally you did something like this:


@Grab('org.springframework:spring-context:4.0.0.RELEASE')

import org.springframework.context.support.GenericApplicationContext
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class Login {

    def authorize(User user){
        if(user.credentials.username == "guest" && user.credentials.password == "guest"){
            "${user.greetings} ${user.credentials.username}"
        }else
            "You are not ${user.greetings}"
    }
}

@Component
class Credentials {
    String username = "guest"
    String password = "guest"
}

@Component
class User{
    @Autowired
    Credentials credentials
    String greetings = "Welcome"
}

def ctx = new GenericApplicationContext()
new ClassPathBeanDefinitionScanner(ctx).scan('') // scan root package for components
ctx.refresh()

def login = ctx.getBean("login")
def user  = ctx.getBean("user")
println login.authorize(user)

One of the benefits that I see is that Groovy removes all the unnecessary boiler plate from Java.

Then, if you wanted to add more flavor to your Groovy Apps using the Grail's BeanBuilder , you needed to do something like this:
@Grab(group='org.slf4j', module='slf4j-simple', version='1.7.5')
@Grab(group='org.grails', module='grails-web', version='2.3.4')

import grails.spring.BeanBuilder
import groovy.transform.ToString

class Login {

    def authorize(User user){
        if(user.credentials.username == "John" && user.credentials.password == "Doe"){
            "${user.greetings} ${user.credentials.username}"
        }else
            "You are not ${user.greetings}"
    }
}

@ToString(includeNames=true)
class Credentials{
    String username
    String password
}

@ToString(includeNames=true)
class User{
    Credentials credentials
    String greetings
}


def bb = new BeanBuilder()

bb.beans {

    login(Login)

    user(User){
        credentials = new Credentials(username:"John", password:"Doe")
        greetings = 'Welcome!!'
    }

}

def ctx = bb.createApplicationContext()

def u = ctx.getBean("user")
println u

def l = ctx.getBean("login")
println l.authorize(u)


And now with the new Spring 4 you can add all the Groovy flavor to your apps (without all the Grails Dependencies) and using the new GroovyBeanDefinitionReader from Spring 4:
@Grab('org.springframework:spring-context:4.0.0.RELEASE')

import org.springframework.context.support.GenericApplicationContext
import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader

import groovy.transform.ToString

class Login {

    def authorize(User user){
        if(user.credentials.username == "John" && user.credentials.password == "Doe"){
            "${user.greetings} ${user.credentials.username}"
        }else
            "You are not ${user.greetings}"
    }
}

@ToString(includeNames=true)
class Credentials{
    String username
    String password
}

@ToString(includeNames=true)
class User{
    Credentials credentials
    String greetings
}


def ctx = new GenericApplicationContext()
def reader = new GroovyBeanDefinitionReader(ctx)

reader.beans {

    login(Login)

    user(User){
        credentials = new Credentials(username:"John", password:"Doe")
        greetings = 'Welcome!!'
    }

}

ctx.refresh()

def u = ctx.getBean("user")
println u

def l = ctx.getBean("login")
println l.authorize(u)


And that's not all, also SpringBoot  gives you even more power using Groovy:

//File: app.groovy
import org.springframework.boot.*
import org.springframework.boot.autoconfigure.*
import org.springframework.stereotype.*
import org.springframework.web.bind.annotation.*
import org.springframework.beans.factory.annotation.*
	
	
@Component
class Login {

    def authorize(User user){
        if(user.credentials.username == "John" && user.credentials.password == "Doe"){
            "${user.greetings} ${user.credentials.username}"
        }else
            "You are not ${user.greetings}"
    }
}

@Component
class Credentials{
    String username
    String password
}

@Component
class User{
    Credentials credentials = new Credentials(username:"John", password:"Doe")
    String greetings = "Welcome!!"
}


@Controller
@EnableAutoConfiguration
class SampleController {

	@Autowired
	def login
		
	@Autowired
	def user

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return login.authorize(user)
    }
}


To run the above code, install springboot  and then just execute:

$ spring run app.groovy

and then go to your browser and open http://localhost:8080  and you see:

Welcome!! John

Congratulations to the Spring Team!!
Keep grooving!!

References:
[1] https://spring.io/blog/2013/12/12/announcing-spring-framework-4-0-ga-release
[2] http://groovy.codehaus.org/Using+Spring+Factories+with+Groovy
[3] http://grails.org/doc/latest/guide/spring.html
[4] http://projects.spring.io/spring-boot/
[5] https://spring.io/guides










Spring Framework Groovy (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Consumer-Driven Contract Testing With Spring Cloud Contract
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!