1、@AllArgsConstructor注解和@Value冲突问题
1.1@AllArgsConstructor注解介绍
@AllArgsConstructor generates a constructor with 1 parameter for each field in your class.
就是用这个注解修饰的类会把里面的变量都生成全参数的构造器
@AllArgsConstructor作用 :
未使用该注解,每个注入的bean都需要进行@Autowired注解
@Component @Slf4j public class test { @Autowired private Demo1Service demo1Service; @Autowired private Demo2Service demo2Service; @Autowired private Demo3Service demo3Service; }
使用该注解
@Component @Slf4j @AllArgsConstructor public class test { private Demo1Service demo1Service; private Demo2Service demo2Service; private Demo3Service demo3Service; }
是不是清爽了不少,@Autowired的默认装配,自动装配对象的,实际上也可以理解为我们装配一个构造器进来,正好和@AllArgsConstructor作用对应起来
1.2@Value注解介绍
@Value注解其实就是属性注入。@Value是使用比较频繁的注解之一,它的作用是将配置文件中key对应的值赋值给它标注的属性。
@Value属性注入功能根据注入的内容来源可分为两类:通过配置文件的属性注入和通过非配置文件的属性注入。
通过配置文件的注入根据配置文件的来源又可分为两类:一类为默认的Spring Boot会自动加载的配置文件application.properties中的属性;另一类为自定义配置文件中的属性,需要先通过@PropertySource加载。
1.3@RequiredArgsConstructor注解介绍
作用于类,用于生成包含 final 和 @NonNull 注解的成员变量的构造方法
@RequiredArgsConstructor(onConstructor =@_(@Autowired))
写在类上面可以代替@AutoWired注解,需要注意的是:在注入的时候需要用final定义,或者使用@notnull注解
1.4冲突问题
当我们使用@AllArgsConstructor注解时,遇到@Value注解的时候,就会出现问题,看下面这段代码
@RestController @AllArgsConstructor @RequestMapping("test") public class TestController { @Value("${test.value}") private String test; private TestService testService; @GetMapping() public String get() { System.out.println(test); return testService.get(); } }
启动项目会遇到以下问题:
*************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.good.base.controller.TestController required a bean of type 'java.lang.String' that could not be found. Action: Consider defining a bean of type 'java.lang.String' in your configuration.
@Value注入会失效,原因时因为@Value注解是通过对象的set方法赋值的,构造方法的执行还在set方法之前, 所以在构造方法中使用变量会变量为null。
1.5解决方法
将AllArgsConstructor改成RequiredArgsConstructor,然后把需要注入的bean改成final类型的,就可以了
@RestController @RequiredArgsConstructor @RequestMapping("test") public class TestController { @Value("${test.value}") private String test; private final TestService testService; @GetMapping() public String get() { System.out.println(test); return testService.get(); } }