Search code examples
javastringspring-bootlombokfinal

How does the lombok constructor differ from the normal constructor (generally and when using the final keyword and when using the @value() keyword)


So i'm working on a project using spring i'm trying to define a string value using the propreties.yml file using @Value("${sthg.sthg}") here is an image of it

@Service
@Transactional
@Slf4j
@AllArgsConstructor
public class GedAuthenticationServiceImpl implements GedAuthenticationService {
    @Value("${app.alfresco.alfresco_urls.alfresco_login_url}")
    private  final String authUrl;

and i get this error

Parameter 0 of constructor in package.class required a bean of type 'java.lang.String' that could not be found.

and if i use the normal constructor like this

@Service
@Transactional
@Slf4j
public class GedAuthenticationServiceImpl implements GedAuthenticationService {
    private  final String authUrl;

    public GedAuthenticationServiceImpl( @Value("${app.alfresco.alfresco_urls.alfresco_login_url}") String authUrl) {
        this.authUrl = authUrl;
    }

it works just finneee

as i said i used the normal constructor but i don't know why it wouldn't work with the other one and i can't seem to get the difference between the too cases


Solution

  • By using @AllArgsConstructor, you are using a Constructor Injection under the hood, by default when you have only ONE constructor in your Spring component class, it will use DI.

    What I mean by under the hood is that Lombok wrote a code similar to this:

    public YourSeviceClass(String test) {
            this.test = test;
    }
    

    And in your example, there no String bean declared in your application, so the Spring container can't inject it.

    Create a separate config class that contains your login configs. Don't mix everything in your service class, it will make you code so ugly and hard to read in the future.

    Example (Use Records if you are using Java 17):

    @ConfigurationProperties(prefix = "app.alfresco...ect")
    public class PropertyConfig {
    
        private String myVariableName;
        ...
    }
    

    Check this for more details: https://www.baeldung.com/configuration-properties-in-spring-boot