Groovy Guide — GroovyBeans: Properties and JavaBeans
In this tutorial, you will learn about Groovy Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
GroovyBeans simplify JavaBean creation with automatic getter/setter generation, named parameter constructors, and property access syntax, making data objects concise and readable.
What You'll Learn
- Defining GroovyBeans with properties
- Automatic getters and setters
- Named parameter constructors
- The @Canonical annotation
- JavaBean integration
Why It Matters
GroovyBeans eliminate boilerplate from data objects. What takes 50 lines in Java takes 5 in Groovy. Durga Antivirus Pro uses GroovyBeans for configuration models.
Real-World Use
POJO alternatives in Groovy, configuration objects, DTOs, and domain models benefit from GroovyBean syntax.
flowchart LR
A["GroovyBeans"] --> B["Properties"]
B --> C["Constructors"]
C --> D["@Canonical"]
D --> E["Java Interop"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
Basic GroovyBean
class Person {
String name
int age
String email
}
def p = new Person()
p.name = "Alice"
p.age = 30
println p.name // "Alice"
Automatic Accessors
class Product {
String name
BigDecimal price
boolean active
}
def product = new Product()
product.name = "Widget" // setter
println product.name // getter
println product.active // boolean getter (isActive)
// All getters/setters are auto-generated
Named Parameter Constructors
class User {
String username
String email
boolean admin
}
// Named parameters
def user = new User(username: "alice", email: "a@example.com", admin: true)
// Partial construction
def guest = new User(username: "guest")
// Works with regular Java classes too
def list = new ArrayList<String>(size: 10)
@Canonical Annotation
import groovy.transform.Canonical
@Canonical
class Point {
int x
int y
}
def p1 = new Point(3, 4)
def p2 = new Point(3, 4)
println p1 // Point(3, 4)
println p1 == p2 // true (equals/hashCode)
@TupleConstructor
import groovy.transform.TupleConstructor
@TupleConstructor
class Customer {
String name
String email
boolean active = true
}
def c = new Customer("Alice", "a@example.com")
def c2 = new Customer("Bob", "b@example.com", false)
@Immutable
import groovy.transform.Immutable
@Immutable
class Config {
String host
int port
boolean ssl
}
def config = new Config("localhost", 8080, false)
// config.host = "other" // Error: immutable
// Automatically has equals, hashCode, toString
GroovyBeans with Methods
class Calculator {
int operand1
int operand2
int sum() { operand1 + operand2 }
int product() { operand1 * operand2 }
}
def calc = new Calculator(operand1: 5, operand2: 3)
println calc.sum() // 8
println calc.product() // 15
Common Mistakes
1. Using public fields directly
GroovyBeans create private fields with public accessors. Direct field access bypasses getters.
2. Immutability confusion
GroovyBeans are mutable by default. Use @Immutable for read-only objects.
3. Missing type in properties
Untyped properties default to Object. Add types for type safety.
4. Boolean property naming
Boolean properties generate isXxx() getters, not getXxx().
5. Constructor ordering
TupleConstructor uses field declaration order. Named parameters are order-independent.
Practice Questions
1. What is a GroovyBean? A class with automatic property accessors, constructors, and JavaBean integration.
2. What does @Canonical generate? equals, hashCode, toString, and a tuple constructor from field declaration order.
3. How do you create an immutable GroovyBean? Use the @Immutable annotation. All fields become read-only with proper equals/hashCode.
Challenge: Create a GroovyBean that represents a bank account with validation in setters.
FAQ
{{< faq question="Are GroovyBeans compatible with Java?" >} Yes. GroovyBeans compile to standard Java bytecode with proper getter/setter methods. {{< /faq >}}
{{< faq question="Can I override auto-generated getters?" >} Yes. Define your own getter method and it takes precedence over the generated one. {{< /faq >}}
{{< faq question="What is @ToString?" >} A transform that generates a toString() method. @Canonical includes it plus equals and hashCode. {{< /faq >}}
{{< faq question="Do GroovyBeans support property change listeners?" >} Yes, with @Bindable or @Vetoable annotations for observable beans. {{< /faq >}}
{{< faq question="Can I use GroovyBeans with Hibernate?" >} Yes, but be careful with proxy generation. Use @Canonical with caution as Hibernate needs default constructor. {{< /faq >}}
Mini Project
Build a GroovyBean-based configuration system:
@Canonical
class DatabaseConfig {
String host = "localhost"
int port = 5432
String database = "app"
String username
String password
}
@Canonical
class AppConfig {
String name
int maxThreads = 4
boolean debug = false
DatabaseConfig database = new DatabaseConfig()
}
def config = new AppConfig(
name: "MyApp",
maxThreads: 10,
debug: true,
database: new DatabaseConfig(database: "myapp_db")
)
println config
What's Next
Now that you understand GroovyBeans, explore closures for Functional Programming.
| Topic | Description | Link |
|---|---|---|
| Groovy Closures | Functional programming | {{< ref "04-closures" >}} |
| Groovy Strings | String operations | {{< ref "05-strings" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro