Designing Objects on Spring
In this pack: sizing and rule strictness are set by the core
plugin's oo-design skill; each rule here keeps a core rule in this
language.
Overview
This skill holds only what Spring changes on top of oo-java: load
that skill too, because its rules on records, equality, refusals and
final classes still hold in a Spring code base. The annotations below
are where a design can slip: a field injected after construction, a
transaction that starts only when a call enters the proxy, an entity
whose setters hand its state to any service, and a repository whose
generic methods reach the domain. Spring Framework 7.0 and Spring Boot
4.1 on Java 21 or later change how these rules are kept, not what they
require.
When to use
- A bean reaches a collaborator through an
@Autowired field or
setter, or asks an ApplicationContext for one.
- A class that holds a domain rule carries
@Service, @Component or
another annotation the container scans.
@Transactional sits on a repository, a domain class or a method
that another method of the same object calls.
- A JPA entity has setters, a public no-argument constructor, or no
constructor that refuses invalid state.
- A Spring Data repository hands
save, delete or another generic
method to domain code.
- Lazy loading still runs while a view renders, after the use case has
returned.
- A controller sends a request record into the domain, or trusts a
request body without Bean Validation.
When not to use
- The code is plain Java with no framework.
oo-java covers that.
- The code runs in Jakarta EE's own container, such as CDI or
enterprise beans with no Spring: outside this skill.
- The question is one no Spring feature changes, such as which object
owns a rule. The core skills answer it, starting from
oo-design.
Core rules
Rule. Inject every collaborator through the one constructor into a
final field: no @Autowired on a field or a setter, and no
ApplicationContext or BeanFactory lookup outside configuration
classes. A class with a single constructor needs no @Autowired,
because Spring uses that constructor and its parameters say what the
object needs before any method runs, as
oo-inverting-dependencies rules 2 and 5 ask. A lookup hides those
needs, and a field or setter injected after construction lets a
half-built object exist.
Default. Keep domain classes free of Spring annotations and
imports, and build them in @Bean methods of @Configuration
classes that read as the composition root; stereotype annotations
and component scanning stay on edge classes such as controllers and
adapters. A @Bean method names the class it builds and the
collaborators it takes, so the configuration reads as the object
graph, while @Service on a domain class moves that decision into a
scan, as oo-inverting-dependencies rules 3 and 4 and
oo-working-within-a-framework rule 2 ask.
The exception is a domain object the use case builds for one call:
its owner builds it with new from values it already holds, so no
@Bean method builds it, and the class still imports nothing from
Spring.
Rule. Put @Transactional on the public method of the application
service that runs one use case, so that one transaction changes one
aggregate, never on a domain class; a call from the same object
starts no transaction, so a unit that needs its own transaction is
reached through another bean or a TransactionTemplate. Only a
call that enters the proxy is intercepted, so a method calling
another @Transactional method of the same object never passes the
proxy. Protected and package-visible methods can be transactional
for class-based proxies; interface-based proxies need public
methods. This keeps oo-placing-domain-logic rule 2,
oo-taming-persistence rule 4 and oo-designing-aggregates rule 4.
Default. A JPA entity that is a domain object keeps its rules:
field access, a protected no-argument constructor that only the
provider calls, a checking constructor or named factory for every
other caller, and methods named for domain actions instead of
setters. Field access lets the provider read and set the fields
directly, so setters are required only with property access. The
checking constructor keeps the invariant the entity holds, and an
action method reads the current state before it changes what the
action allows, as oo-encapsulating-state-and-behaviour rules 1 and
2, oo-constructing-valid-objects rule 3 and
oo-working-within-a-framework rule 1 ask.
The exception is an entity whose mapped superclass maps by property
access: the provider then reads and writes through accessors, so
they stay protected and callers use the entity's action methods,
which still name each change.
Rule. Reach another aggregate by its identity, never by a mapped
association to its root, and set spring.jpa.open-in-view=false so
that no lazy load runs after the use case's transaction has ended.
Holding the other aggregate's object lets one change cross two
boundaries, and an open entity manager keeps the session alive
through the view, so a lazy association loads after the commit.
Identity and a repository keep each aggregate whole, as
oo-taming-persistence rule 5 and oo-designing-aggregates rule 3
ask.
Default. Check a request's shape with Bean Validation on a request
record, with @Valid on the @RequestBody parameter, then build the
domain's values from it in one place; no domain class receives the
request record. A failed check raises
MethodArgumentNotValidException, which Spring answers with a 400,
and the edge then turns the record into values through their
constructors, as oo-placing-domain-logic rule 5 and
oo-crossing-system-boundaries rules 1 and 2 ask.
The exception is a request with several parts, such as a body and a
file: @Valid on each @RequestPart applies Bean Validation to the
part, the file's size and type are checked at the edge, and the
domain's values are still built in that one place.
Rule. Declare the repository the domain uses in domain types,
importing nothing from Spring, and implement it at the edge with an
adapter class that delegates to a Spring Data interface exposing
only the methods the adapter needs; the generic methods of
JpaRepository never reach domain code. The domain's interface
names the calls the domain makes, the adapter implements them in
Spring's types, and the Spring Data interface copies only the
methods the adapter delegates to, so a CRUD repository's complete
set of methods stops at the edge, as
oo-designing-repositories rules 1 and 2 ask.
Rule. Leave non-final exactly the classes Spring or the
persistence provider subclasses: a @Configuration class whose
proxyBeanMethods is true, which relaxes oo-java rule 7; a bean
Spring proxies through its class, which under Spring Boot's default
(spring.aop.proxy-target-class=true) is any bean whose methods
carry @Transactional, whether or not it implements an interface,
which relaxes oo-java rule 7; and a JPA entity, which relaxes
oo-java rule 7; every other class keeps that rule. A final class
cannot be proxied, a final method cannot be advised, a
configuration class with proxyBeanMethods true needs a runtime
subclass, and the provider requires an entity to be non-final.
oo-honouring-substitutability rule 5 still asks every other class
to be closed.
Pattern
RefillEligibility decides whether a prescription may be dispensed
again, from the date it was last dispensed and the current time, within
the clinic's refill interval. It is a domain class: a rule the clinic
owns, not a bean the container describes.
Before:
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RefillEligibility {
@Autowired
private Clock clock;
public boolean allows(Instant lastDispensedAt) {
return !clock.instant().isBefore(
lastDispensedAt.plus(Duration.ofDays(28)));
}
}
In the Before, @Service puts a stereotype on a domain class (rule 2),
and @Autowired on the field hides the clock from the constructor
(rule 1). Spring sets clock after construction, so nothing in the
class says what it needs and a half-built object can exist. The fence
stores nothing.
After:
import java.time.Duration;
import java.time.Instant;
public final class RefillEligibility {
private final Duration interval;
public RefillEligibility(Duration interval) {
this.interval = interval;
}
public boolean allows(Instant lastDispensedAt, Instant now) {
return !now.isBefore(lastDispensedAt.plus(interval));
}
}
import java.time.Clock;
import java.time.Instant;
public final class CheckRefillEligibility {
private final Clock clock;
private final RefillEligibility eligibility;
public CheckRefillEligibility(
Clock clock, RefillEligibility eligibility) {
this.clock = clock;
this.eligibility = eligibility;
}
public boolean isEligible(Instant lastDispensedAt) {
Instant now = clock.instant();
return eligibility.allows(lastDispensedAt, now);
}
}
import java.time.Clock;
import java.time.Duration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RefillConfiguration {
@Bean
Clock clock() {
return Clock.systemUTC();
}
@Bean
RefillEligibility refillEligibility() {
return new RefillEligibility(Duration.ofDays(28));
}
@Bean
CheckRefillEligibility checkRefillEligibility(
Clock clock, RefillEligibility eligibility) {
return new CheckRefillEligibility(clock, eligibility);
}
}
In the After, RefillEligibility has no Spring annotation or import,
keeps the clinic's refill interval in a final Duration field, and
takes the current time as a value in allows, which keeps
oo-designing-for-testability rule 3. CheckRefillEligibility keeps
rule 1: it receives the clock and the domain class through one
constructor into final fields, and isEligible asks the clock once and
passes the answer on. RefillConfiguration is the composition root:
its @Bean methods name each object and the values or collaborator it
takes, and the domain class is built there from Duration.ofDays(28),
which keeps rule 2. RefillEligibility and CheckRefillEligibility
are final, because neither is a @Configuration class or a bean
Spring proxies, which keeps oo-java rule 7. RefillConfiguration is
non-final because a @Configuration class is subclassed at startup,
which relaxes oo-java rule 7. None of the fences stores anything.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
@Autowired on a field or a setter.
@Service or @Component on a class that holds a domain rule.
- A call to
ApplicationContext or BeanFactory outside configuration.
@Transactional on a repository or a domain class.
- One method of a bean calling another
@Transactional method of the
same object.
- A JPA entity with a setter or a public no-argument constructor.
- A mapped association to another aggregate root.
spring.jpa.open-in-view left true.
- A repository interface that extends
JpaRepository and reaches
domain code.
- A
final class whose methods carry @Transactional.
- A controller that takes a request record and passes it into the
domain.
Common mistakes
- Adding
@Autowired to a class that has one constructor, where Spring
already uses it.
- Moving a rule into a
@Service domain class so that injection is
convenient.
- Marking a method
@Transactional and calling it from the same object,
expecting a new transaction.
- Adding setters to a JPA entity because the provider needs them; field
access needs none.
- Mapping another aggregate as an association because lazy loading
seems to make it easy.
- Letting a
JpaRepository become the repository type the domain
names.
- Making a
@Configuration class final while proxyBeanMethods stays
true.
- Sending a
@RequestBody record into the domain instead of building
domain values at the edge.
Related skills
oo-java holds the language rules this skill applies, including rule
7 on final classes.
oo-inverting-dependencies decides how collaborators reach an object
and where the composition root sits.
oo-working-within-a-framework decides what a framework may shape and
what stays in the domain.
oo-placing-domain-logic keeps an application service to
coordination.
oo-taming-persistence sets the unit of work and keeps a lazy load
inside its transaction.
oo-designing-aggregates decides what one transaction changes and how
aggregates refer to each other.
oo-encapsulating-state-and-behaviour keeps state behind methods
named for domain actions.
oo-constructing-valid-objects makes a constructor refuse broken
input.
oo-crossing-system-boundaries gives each contract its own transfer
types.
oo-designing-repositories declares a repository in domain types.
oo-honouring-substitutability decides which classes stay open.
Further reading
- Transactions through the proxy
1---2name: oo-java-spring3description: Use when Java code on Spring wires beans with @Autowired or annotations, places @Transactional, or gives a JPA entity setters instead of its own rules.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-java-spring7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Designing Objects on Spring1213**In this pack:** sizing and rule strictness are set by the core14plugin's `oo-design` skill; each rule here keeps a core rule in this15language.1617## Overview1819This skill holds only what Spring changes on top of `oo-java`: load20that skill too, because its rules on records, equality, refusals and21final classes still hold in a Spring code base. The annotations below22are where a design can slip: a field injected after construction, a23transaction that starts only when a call enters the proxy, an entity24whose setters hand its state to any service, and a repository whose25generic methods reach the domain. Spring Framework 7.0 and Spring Boot264.1 on Java 21 or later change how these rules are kept, not what they27require.2829## When to use3031- A bean reaches a collaborator through an `@Autowired` field or32 setter, or asks an `ApplicationContext` for one.33- A class that holds a domain rule carries `@Service`, `@Component` or34 another annotation the container scans.35- `@Transactional` sits on a repository, a domain class or a method36 that another method of the same object calls.37- A JPA entity has setters, a public no-argument constructor, or no38 constructor that refuses invalid state.39- A Spring Data repository hands `save`, `delete` or another generic40 method to domain code.41- Lazy loading still runs while a view renders, after the use case has42 returned.43- A controller sends a request record into the domain, or trusts a44 request body without Bean Validation.4546## When not to use4748- The code is plain Java with no framework. `oo-java` covers that.49- The code runs in Jakarta EE's own container, such as CDI or50 enterprise beans with no Spring: outside this skill.51- The question is one no Spring feature changes, such as which object52 owns a rule. The core skills answer it, starting from `oo-design`.5354## Core rules55561. Rule. **Inject every collaborator through the one constructor into a57 final field: no `@Autowired` on a field or a setter, and no58 `ApplicationContext` or `BeanFactory` lookup outside configuration59 classes.** A class with a single constructor needs no `@Autowired`,60 because Spring uses that constructor and its parameters say what the61 object needs before any method runs, as62 `oo-inverting-dependencies` rules 2 and 5 ask. A lookup hides those63 needs, and a field or setter injected after construction lets a64 half-built object exist.65662. Default. **Keep domain classes free of Spring annotations and67 imports, and build them in `@Bean` methods of `@Configuration`68 classes that read as the composition root; stereotype annotations69 and component scanning stay on edge classes such as controllers and70 adapters.** A `@Bean` method names the class it builds and the71 collaborators it takes, so the configuration reads as the object72 graph, while `@Service` on a domain class moves that decision into a73 scan, as `oo-inverting-dependencies` rules 3 and 4 and74 `oo-working-within-a-framework` rule 2 ask.7576 The exception is a domain object the use case builds for one call:77 its owner builds it with `new` from values it already holds, so no78 `@Bean` method builds it, and the class still imports nothing from79 Spring.80813. Rule. **Put `@Transactional` on the public method of the application82 service that runs one use case, so that one transaction changes one83 aggregate, never on a domain class; a call from the same object84 starts no transaction, so a unit that needs its own transaction is85 reached through another bean or a `TransactionTemplate`.** Only a86 call that enters the proxy is intercepted, so a method calling87 another `@Transactional` method of the same object never passes the88 proxy. Protected and package-visible methods can be transactional89 for class-based proxies; interface-based proxies need public90 methods. This keeps `oo-placing-domain-logic` rule 2,91 `oo-taming-persistence` rule 4 and `oo-designing-aggregates` rule 4.92934. Default. **A JPA entity that is a domain object keeps its rules:94 field access, a `protected` no-argument constructor that only the95 provider calls, a checking constructor or named factory for every96 other caller, and methods named for domain actions instead of97 setters.** Field access lets the provider read and set the fields98 directly, so setters are required only with property access. The99 checking constructor keeps the invariant the entity holds, and an100 action method reads the current state before it changes what the101 action allows, as `oo-encapsulating-state-and-behaviour` rules 1 and102 2, `oo-constructing-valid-objects` rule 3 and103 `oo-working-within-a-framework` rule 1 ask.104105 The exception is an entity whose mapped superclass maps by property106 access: the provider then reads and writes through accessors, so107 they stay `protected` and callers use the entity's action methods,108 which still name each change.1091105. Rule. **Reach another aggregate by its identity, never by a mapped111 association to its root, and set `spring.jpa.open-in-view=false` so112 that no lazy load runs after the use case's transaction has ended.**113 Holding the other aggregate's object lets one change cross two114 boundaries, and an open entity manager keeps the session alive115 through the view, so a lazy association loads after the commit.116 Identity and a repository keep each aggregate whole, as117 `oo-taming-persistence` rule 5 and `oo-designing-aggregates` rule 3118 ask.1191206. Default. **Check a request's shape with Bean Validation on a request121 record, with `@Valid` on the `@RequestBody` parameter, then build the122 domain's values from it in one place; no domain class receives the123 request record.** A failed check raises124 `MethodArgumentNotValidException`, which Spring answers with a 400,125 and the edge then turns the record into values through their126 constructors, as `oo-placing-domain-logic` rule 5 and127 `oo-crossing-system-boundaries` rules 1 and 2 ask.128129 The exception is a request with several parts, such as a body and a130 file: `@Valid` on each `@RequestPart` applies Bean Validation to the131 part, the file's size and type are checked at the edge, and the132 domain's values are still built in that one place.1331347. Rule. **Declare the repository the domain uses in domain types,135 importing nothing from Spring, and implement it at the edge with an136 adapter class that delegates to a Spring Data interface exposing137 only the methods the adapter needs; the generic methods of138 `JpaRepository` never reach domain code.** The domain's interface139 names the calls the domain makes, the adapter implements them in140 Spring's types, and the Spring Data interface copies only the141 methods the adapter delegates to, so a CRUD repository's complete142 set of methods stops at the edge, as143 `oo-designing-repositories` rules 1 and 2 ask.1441458. Rule. **Leave non-final exactly the classes Spring or the146 persistence provider subclasses: a `@Configuration` class whose147 `proxyBeanMethods` is true, which relaxes `oo-java` rule 7; a bean148 Spring proxies through its class, which under Spring Boot's default149 (`spring.aop.proxy-target-class=true`) is any bean whose methods150 carry `@Transactional`, whether or not it implements an interface,151 which relaxes `oo-java` rule 7; and a JPA entity, which relaxes152 `oo-java` rule 7; every other class keeps that rule.** A final class153 cannot be proxied, a final method cannot be advised, a154 configuration class with `proxyBeanMethods` true needs a runtime155 subclass, and the provider requires an entity to be non-final.156 `oo-honouring-substitutability` rule 5 still asks every other class157 to be closed.158159## Pattern160161`RefillEligibility` decides whether a prescription may be dispensed162again, from the date it was last dispensed and the current time, within163the clinic's refill interval. It is a domain class: a rule the clinic164owns, not a bean the container describes.165166Before:167168```java169import java.time.Clock;170import java.time.Duration;171import java.time.Instant;172import org.springframework.beans.factory.annotation.Autowired;173import org.springframework.stereotype.Service;174175@Service176public class RefillEligibility {177 @Autowired178 private Clock clock;179180 public boolean allows(Instant lastDispensedAt) {181 return !clock.instant().isBefore(182 lastDispensedAt.plus(Duration.ofDays(28)));183 }184}185```186187In the Before, `@Service` puts a stereotype on a domain class (rule 2),188and `@Autowired` on the field hides the clock from the constructor189(rule 1). Spring sets `clock` after construction, so nothing in the190class says what it needs and a half-built object can exist. The fence191stores nothing.192193After:194195```java196import java.time.Duration;197import java.time.Instant;198199public final class RefillEligibility {200 private final Duration interval;201202 public RefillEligibility(Duration interval) {203 this.interval = interval;204 }205206 public boolean allows(Instant lastDispensedAt, Instant now) {207 return !now.isBefore(lastDispensedAt.plus(interval));208 }209}210```211212```java213import java.time.Clock;214import java.time.Instant;215216public final class CheckRefillEligibility {217 private final Clock clock;218 private final RefillEligibility eligibility;219220 public CheckRefillEligibility(221 Clock clock, RefillEligibility eligibility) {222 this.clock = clock;223 this.eligibility = eligibility;224 }225226 public boolean isEligible(Instant lastDispensedAt) {227 Instant now = clock.instant();228 return eligibility.allows(lastDispensedAt, now);229 }230}231```232233```java234import java.time.Clock;235import java.time.Duration;236import org.springframework.context.annotation.Bean;237import org.springframework.context.annotation.Configuration;238239@Configuration240public class RefillConfiguration {241 @Bean242 Clock clock() {243 return Clock.systemUTC();244 }245246 @Bean247 RefillEligibility refillEligibility() {248 return new RefillEligibility(Duration.ofDays(28));249 }250251 @Bean252 CheckRefillEligibility checkRefillEligibility(253 Clock clock, RefillEligibility eligibility) {254 return new CheckRefillEligibility(clock, eligibility);255 }256}257```258259In the After, `RefillEligibility` has no Spring annotation or import,260keeps the clinic's refill interval in a final `Duration` field, and261takes the current time as a value in `allows`, which keeps262`oo-designing-for-testability` rule 3. `CheckRefillEligibility` keeps263rule 1: it receives the clock and the domain class through one264constructor into final fields, and `isEligible` asks the clock once and265passes the answer on. `RefillConfiguration` is the composition root:266its `@Bean` methods name each object and the values or collaborator it267takes, and the domain class is built there from `Duration.ofDays(28)`,268which keeps rule 2. `RefillEligibility` and `CheckRefillEligibility`269are final, because neither is a `@Configuration` class or a bean270Spring proxies, which keeps `oo-java` rule 7. `RefillConfiguration` is271non-final because a `@Configuration` class is subclassed at startup,272which relaxes `oo-java` rule 7. None of the fences stores anything.273274## Red flags275276Places to look, not verdicts. A red flag becomes a finding only with277evidence: a measurement, a reproducible bug, or a failing test.278279- `@Autowired` on a field or a setter.280- `@Service` or `@Component` on a class that holds a domain rule.281- A call to `ApplicationContext` or `BeanFactory` outside configuration.282- `@Transactional` on a repository or a domain class.283- One method of a bean calling another `@Transactional` method of the284 same object.285- A JPA entity with a setter or a public no-argument constructor.286- A mapped association to another aggregate root.287- `spring.jpa.open-in-view` left true.288- A repository interface that extends `JpaRepository` and reaches289 domain code.290- A `final` class whose methods carry `@Transactional`.291- A controller that takes a request record and passes it into the292 domain.293294## Common mistakes295296- Adding `@Autowired` to a class that has one constructor, where Spring297 already uses it.298- Moving a rule into a `@Service` domain class so that injection is299 convenient.300- Marking a method `@Transactional` and calling it from the same object,301 expecting a new transaction.302- Adding setters to a JPA entity because the provider needs them; field303 access needs none.304- Mapping another aggregate as an association because lazy loading305 seems to make it easy.306- Letting a `JpaRepository` become the repository type the domain307 names.308- Making a `@Configuration` class final while `proxyBeanMethods` stays309 true.310- Sending a `@RequestBody` record into the domain instead of building311 domain values at the edge.312313## Related skills314315- `oo-java` holds the language rules this skill applies, including rule316 7 on final classes.317- `oo-inverting-dependencies` decides how collaborators reach an object318 and where the composition root sits.319- `oo-working-within-a-framework` decides what a framework may shape and320 what stays in the domain.321- `oo-placing-domain-logic` keeps an application service to322 coordination.323- `oo-taming-persistence` sets the unit of work and keeps a lazy load324 inside its transaction.325- `oo-designing-aggregates` decides what one transaction changes and how326 aggregates refer to each other.327- `oo-encapsulating-state-and-behaviour` keeps state behind methods328 named for domain actions.329- `oo-constructing-valid-objects` makes a constructor refuse broken330 input.331- `oo-crossing-system-boundaries` gives each contract its own transfer332 types.333- `oo-designing-repositories` declares a repository in domain types.334- `oo-honouring-substitutability` decides which classes stay open.335336## Further reading337338- [Transactions through the proxy](references/transactions-through-the-proxy.md)