akop
akop

Reputation: 7855

HowTo Dependency-Injection with Lombok

I'm searching for a elegant way, to define fields in standard spring-service.
Without lombok our service looks like this:

@Service
public class ServiceA {

   private final String applicationName;
   private final SpecialHandler specialHandler;
   private final ServiceC serviceC;

   public ServiceA(final ConfigBean config,
                  final ServiceB serviceB,
                  final ServiceC serviceC) {
      this.applicationName = config.getBaseConfig().getApplicationInfo().getName();
      this.specialHander = serviceB.getSpecialForAppName(this.applicationName);

      // PROBLEM: each direct dependency forces us to write more and more manual code
      this.serviceC = serviceC;
   }

}

Now, our team want to use the lombok-constructor only (so we can easily add other services). The service above will now look this:

@Service
@RequiredArgsConstructor
public class ServiceA {

   private final ServiceC service;
   // ^- with lombok, this is very pretty and simpel

   private final ConfigBean config;
   private final SpecialHandler specialHandler;
   // ^- PROBLEM: these fields only used in the "createFields()"-method
   // can we inline them somehow?

   private String applicationName;
   private SpecialHandler specialHanlder;
   // ^- PROBLEM: these fields are not final anymore
   // can we "make fields final again"?

   @PostConstruct
   public void createFields() { // maybe we can put parameters to the post-construct?
      this.applicationName = this.config.getBaseConfig().getApplicationInfo().getName();
      this.specialHander = this.serviceB.getSpecialForAppName(this.applicationName); 
   }

}

Question

How can I solve the issues (mentioned in the sourceCode-comments)?

Footnote

I saw this "problem" in many projects. The variants, which I mentioned above, are the only solutions I saw yet. Both solutions getting more ugly when raising the number of fields.

Upvotes: 0

Views: 1475

Answers (1)

QuentinC
QuentinC

Reputation: 14752

Lombok only writes boilerplate code for you. It means that, as soon as you have anything non trivial to do, you can't use it anymore. So if you want to keep your fields computed in the constructor final, you will have to write the constructor by hand.

As far as I know, a @PostConstruct method can't accept any parameter either.

There are two possibles tracks to follow:

  • you can certainly use field-based or setter-based injection, using @Autowired annotation.
  • Pass an already constructed SpecialHandler to your service. You can do so, , rather than using @Service annotation, by creating it in a @Bean method inside a @Configuration class for example.

Upvotes: 2

Related Questions