简体   繁体   中英

Using dependency injection on class having parameterized constructor

I have a custom class which has a parameterized constructor

@Component
public class ExtractDataFromImage implements ExtractData{

    private Map<String, Boolean> selectedOptions;
    private BufferedImage image;
    
    @Autowired
    private TesseractService tesseractService;
    
    public ExtractDataFromImage(
            Map<String, Boolean> selectedOptions, 
            BufferedImage image,
            TesseractService tesseractService
            ) {
        this.selectedOptions = selectedOptions;
        this.image = image;
        this.tesseractService = tesseractService;
    }
    
    @Override
    public Map<String, ArrayList<String>> extractData() {
        //code
    }
}

So there are 3 parameters required at the time of instantiation. If I want to add this class as a dependency, I found that there is no direct way to do this in Spring.

I am aware that I can simply create a new instance of my class and use it's methods. But I am not finding any direct way to inject this class in my another class, which is a Rest controller.

Thing to note: All 3 parameters need to passed at runtime. I cannot use them from properties file

Even if there is no direct way in Spring, I would like to know what is the best way to define a dependency on this class and also create a new instance using the parameterized constructor

What you are looking for is a Spring constructor dependency injection . There are 3 ways to inject your dependency in Spring: class field , contructor and by a setter method .

The best and recommanded way is the constructor dependency injection. In your case, you have to set an @Autowired annotation on your constructor (which is not mandatory since Spring 4.3) and remove the @Autowired annotation from your field private TesseractService tesseractService; .

@Autowired
public ExtractDataFromImage(
            Map<String, Boolean> selectedOptions, 
            BufferedImage image,
            TesseractService tesseractService
            ) {
        this.selectedOptions = selectedOptions;
        this.image = image;
        this.tesseractService = tesseractService;
}
@RestController
public class YourController {

    private ExtractDataFromImage edfi;

    @Autowired
    public YourController(ExtractDataFromImage edfi) {
        this.edfi = edfi;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM