-1

I wrote a simple example by use java configuration for start learn Spring framework, but it only passed in unit test, not in main function.

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

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

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

// ---------

@Component
public class JayCD implements CompactDisc {

  public void play() {
    System.out.println("Playing A CD");
  }
}

// ---------


@Configuration
@ComponentScan
public class CDPlayerConfig {

}

// ---------

public class Main {

    @Autowired
    static MediaPlayer mediaPlayer;

    @Autowired
    static CompactDisc compactDisc;

    public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
        mediaPlayer.play();
    }
}

mediaPlayer is NULL?? Why is the use of annotations unsuccessful? How to modify code? Thanks!

  • try to annotate `Main` as `@Component` – dehasi Apr 18 '19 at 13:51
  • Your `mediaPlayer` is `null`, because this field hasn't been initialized yet. I found a similar questions https://stackoverflow.com/questions/17659875/autowired-and-static-method – theexiile1305 Apr 18 '19 at 14:00

2 Answers2

0

The @Autowired annotation can be used for the class that you have marked with the @Component annotation.

You have marked @Component the class JayCD and you can use @Autowired for the class JayCD not for the implemented class.

And you needn' t to use @Autowired on the constructor of a class marked @Component.

I'm a spring starter but I think that my answer is right.

Sorry for my english

0

@Autowired annotation will only be evalued in instances managed by spring. (annotated @Service or @Component by exemple)

In your case, mediaPlayer will not be initialized because Main is not Managed by spring.

A solution could be this one :

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

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

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

// ---------

@Component
public class JayCD implements CompactDisc {

  public void play() {
    System.out.println("Playing A CD");
  }
}

// ---------


@Configuration
@ComponentScan
public class CDPlayerConfig {

}

// ---------

@Component
public class Main {

    @Autowired
    private MediaPlayer mediaPlayer;

    @Autowired
    private CompactDisc compactDisc;

    public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(CDPlayerConfig.class);
        context.getBean(Main.class).run(); //This will execute run method in a spring context
    }

    public run(){
        mediaPlayer.play();
    }
}

However your Main.compactDisc attribute seems useless here

Mathiewz
  • 189
  • 1
  • 12