Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete the autowire from controller and replace it with normal initialization

My current codes contain @autowired but I would like to remove it and then initialize it with code. Please vote down my questions if you found it hard to understand but PLEASE at least comment so that I can re-edit as I am new to this annotation stuff and still getting my hands wet with it.

Below shows my code and from what I could understand about autowired is that it takes the values from class "Test" and wire the values to testing. What about if I remove this @autowired from the code? How can I still make it executable? I mean, if I remove the @autowired, how can I still initialized the values in this same line instead of using the wiring annotation? - Reason I wanted to try this is to see my understanding and at the same time see more different examples to improve my understranding

 @Autowired
  @Qualifier("testing")
  Test testing;

I dont have expected results because I just want to understand the annotations and see whether my understanding is correct.

like image 306
kingkongman oftheworldinchaos Avatar asked Aug 12 '26 10:08

kingkongman oftheworldinchaos


1 Answers

There are three ways to inject an autowired dependency (using spring) into a bean:

  1. Autowiring the field itself

    @Autowired
    private Test test;
    
    @Autowired
    private SomethingService somethingService;
    
  2. Autowiring a setter

    private Test test;
    private SomethingService somethingService;
    
    @Autowired
    public void setTest(Test test) {
        this.test = test;
    }
    
    @Autowired
    public void setSomethingService(SomethingService somethingService) {
        this.somethingService = somethingService;
    }
    
  3. Autowiring the constructor (which doesn't need an annotation):

    public class Something {
    
        private Test test;
        private SomethingService somethingService;
    
        public Something(Test test, SomethingService somethingService) {
            this.test = test;
            this.somethingService = somethingService;
        }
    
        ...
    }
    

A benefit of using the third approach is that when you construct an instance of the class for testing, you can pass in any implementations you want for the dependencies.

like image 125
Jason Avatar answered Aug 15 '26 00:08

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!