Best practice for @Value fields, Lombok, and Constructor Injection?

前端 未结 1 1715
走了就别回头了
走了就别回头了 2021-02-18 15:05

I\'m developing a Java Spring application. I have some fields in my application which are configured using a .yml config file. I would like to import those values using an @Va

相关标签:
1条回答
  • 2021-02-18 15:59

    You need @RequiredArgsConstructor and mark myDependency as final. In this case, Lombok will generate a constructor based on 'required' final filed as argument, for example:

    @RequiredArgsConstructor
    @Service
    public class MyService {
    
        @Value("${my.config.value}")
        private String myField;
    
        private final MyComponent myComponent;
    
        //...
    }
    

    That is equal the following:

    @Service
    public class MyService {
    
        @Value("${my.config.value}")
        private String myField;
    
        private final MyComponent myComponent;
    
        public MyService(MyComponent myComponent) { // <= implicit injection
            this.myComponent = myComponent;
        } 
    
        //...
    }
    

    Since here is only one constructor, Spring inject MyComponent without the explicit use of the @Autowired annotation.

    0 讨论(0)
提交回复
热议问题