如何在Spring中使用自动装配注释

时间:2019-04-18 13:48:44

标签: java spring

我通过使用Java配置编写了一个简单的示例,以开始学习Spring框架,但它仅在单元测试中通过,而未在main函数中通过。

@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为NULL? 为什么注释使用不成功?如何修改代码? 谢谢!

3 个答案:

答案 0 :(得分:0)

@Autowired批注可用于已用@Component批注标记的类。

您已将@Component标记为JayCD类,并且可以将@Autowired用于JayCD类,而不用于已实现的类。

您不必在标有@Component的类的构造函数上使用@Autowired。

我是一名初学者,但我认为我的回答是正确的。

对不起,我的英语水平

答案 1 :(得分:0)

# open a pointer to the video file stream vs = cv2.VideoCapture(video_path) # check if video requires rotation rotateCode = check_rotation(video_path) # loop over frames from the video file stream while True: # grab the frame from the file grabbed, frame = vs.read() # if frame not grabbed -> end of the video if not grabbed: break # check if the frame needs to be rotated if rotateCode is not None: frame = correct_rotation(frame, rotateCode) 注释仅在spring管理的实例中进行赋值。 (例如,用@Autowired@Service注释)

在您的情况下,由于Main不是由spring管理的,因此不会初始化mediaPlayer。

解决方案可能就是这样:

@Component

但是您的@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(); } } 属性在这里似乎没用

答案 2 :(得分:-2)

您的界面必须是最终的

private final CompactDisc cd;

确保您的自动装配类具有批注@Service或@Component

相关问题