0
package soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MediaPlayer {
    private CompactDisc cd;

    @Autowired
    public CDPlayer(CompactDisc cd) {
        this.cd = cd;
    }

    public void play() {
        cd.play();
    }
}

Here the autowiring can be directly applied on the reference variable, then what is the benefit of doing it via the constructor?

package soundsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MediaPlayer {

    @Autowired
    private CompactDisc cd;

    public void play() {
        cd.play();
    }
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
codeengi
  • 11
  • 4

0 Answers0