4

I created a simple rest service using java, and springboot. here is my service layer code

@Service
class MyService {
    private final TestService service;

    @Autowired
    public MyService(final TestService service) {
        this.service = service;
    }

    // here is the issue
    private final Predicate<User> userPredicate = (user) -> this.service.isValidUser(user);
}

In the above line, the ide complaining about the variable service might not be initialized, and I can not use it in the predicate implementation. I tried removing final to the service, that works, but I do not want to remove final to the TestService declaration.

Anyone have any solution ?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
user3470629
  • 511
  • 1
  • 8
  • 20

1 Answers1

6

Execution order is: First all initializing expressions are resolved in lexical order (top to bottom through the file), then the constructor runs.

In other words, that userPredicate = line runs before your this.service = service; line. It's doomed to failure, and the compiler knows it, so it will refuse to compile this code.

The fix is trivial - move that userPredicate initialization into the constructor:

private final TestService service;
private final Predicate<User> userPredicate;

@AutoWired
public MyService(TestService service) {
  this.service = service;
  this.userPredicate = user -> service.isValidUser(user);
}

For what its worth, if you don't need the service for anything except making that userPredicate, might as well get rid of the service field entirely.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72