To take a cue from PHP

50 views
Skip to first unread message

Clemens Gogolin

unread,
Apr 27, 2025, 2:24:59 PMApr 27
to Project Lombok

In PHP, there is a construct that I find very elegant and which is great for Lombok. It saves code in the usual Spring constructor injections:

In PHP, you can write the following:

php

public function __construct( private readonly PersistenceManager $persistenceManager ) { }

Then, in the background, it results in the following:

php

private readonly PersistenceManager $persistenceManager; public function __construct( private readonly PersistenceManager $persistenceManager ) { $this->persistenceManager = $persistenceManager; }

This simplification could also be implemented in Lombok, right?

For example, in Java:

java

MyClass(@InjectService UserRepository userRepository) {}

What do you think?

Thanks for your feedback...


Jan Materne

unread,
Apr 27, 2025, 3:05:40 PMApr 27
to project...@googlegroups.com

Why not

@RequireArgsConstructor
class MyClass {
  final MyService service;
}

Jan


--
You received this message because you are subscribed to the Google Groups "Project Lombok" group.
To unsubscribe from this group and stop receiving emails from it, send an email to project-lombo...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/project-lombok/d0eb2dd4-52cc-426b-a2b2-a075214c0ad7n%40googlegroups.com.

Chris Becker

unread,
Apr 28, 2025, 3:15:47 AMApr 28
to project...@googlegroups.com

Why not use the default injection Annotations (@Inject, @Autowired) into member variables, that most such frameworks provide?
Why do you need a constructor for that?


Jan Materne

unread,
Apr 28, 2025, 4:39:03 AMApr 28
to project...@googlegroups.com

That's the Diskussion "field Injektion vs. Constructor injection". Ctor injection makes the dependencies visible which should be better for unit tests without DI framework.


Clemens Gogolin

unread,
Apr 30, 2025, 5:54:17 AMApr 30
to Project Lombok
I hadn't thought of that. But @RequireArgsConstructor generates a private constructor with a static factory method, and how can I extend the generated constructor? Wouldn't it be easier if I wrote my constructor flexibly and the injected elements (which don't necessarily have to come from a framework) then get a suitable field (optionally with a @getter / @setter)?

Then you save yourself the usual: private final Foo foo; and in the constructor: this.foo = foo;
Reply all
Reply to author
Forward
0 new messages