Home  >  Article  >  Java  >  How to use @RequiredArgsConstructor instead of @Autowired in Java?

How to use @RequiredArgsConstructor instead of @Autowired in Java?

PHPz
PHPzforward
2023-05-08 19:07:061479browse

Use @ConfigurationProperties instead of @Value

Use method

Define the entity of the corresponding field

@Data
// 指定前缀
@ConfigurationProperties(prefix = "developer")
@Component
public class DeveloperProperty {
    private String name;
    private String website;
    private String qq;
    private String phoneNumber;
}

Inject this bean when using it

@RestController
@RequiredArgsConstructor
public class PropertyController {
 
    final DeveloperProperty developerProperty;
 
    @GetMapping("/property")
    public Object index() {
       return developerProperty.getName();
    }
}

We all know that there are three ways to inject a bean (set injection, constructor injection, annotation injection). Spring recommends that we use the constructor method to inject beans.

Let’s take a look at the above code after compiling it. Looks like

How to use @RequiredArgsConstructor instead of @Autowired in Java?

The above is the detailed content of How to use @RequiredArgsConstructor instead of @Autowired in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete