Issue
I have Spring bean
@Component
public class CustomUriBuilder {
private final String cUrl;
private final String redirectUri;
private final String clientId;
public CustomUriBuilder (@Value("${project.url}") String cUrl,
@Value("${project.redirect.url}") String redirectUri, @Value("${project.client-id}") String clientId) {
this.cUrl= cUrl;
this.redirectUri = redirectUri;
this.clientId = clientId;
}
//No default constructor
}
I need to inject this bean in another bean
@Component
public class LinksBuilder {
@Autowired
private final CustomUriBuilder customUriBuilder ;
//No constructors
}
But i got compilation error
Error:(21, 34) java: variable customUriBuilder not initialized in the default constructor
At the same time i am injecting LinksBuilder
(as final) in another controller without any problems
@RestController
@RequestMapping(produces = "application/json")
public class resourceV4 {
private final LinksBuilder linksBuilder;
//No constructors
.
}
Why in the first case it gives an error but in the second case it is working fine?
Solution
Since spring 4.3 there is a feature - you can not add Autowired
annotation for the final fields injection
You must have a constructor initialization for the final fields. I can not see one for the LinksBuilder and resourceV4. See lombok @RequiredArgsContructor
for short.
It is impossible that one class with a final field is compiled ok and without constructor, but another one with an error.
Run other compilers or build ways (terminal gradlew/maven etc) to clarify the situation for you
Answered By - Artem Ptushkin