0

I have a simple Spring Boot web project, right from a template:

@SpringBootApplication
@RestController
public class HelloWorldRestApplication {

public static void main(String[] args) {
    SpringApplication.run(HelloWorldRestApplication.class, args);

    Performer p = new Performer();
    p.perform();
    }
}

I have a test to ensure autowiring works, and in fact it does in this test class (examples come from Spring in Action, 4th):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=CDPlayerConfig.class)
public class CDPlayerTest {

@Autowired
private CDPlayer cdp;

@Test
public void cdShouldNotBeNull(){
    assertNotNull(cdp);
    }
}

and:

public class Performer {

@Autowired
private CDPlayer cdp;

public void perform(){
    System.out.println(cdp);
    cdp.play();
}

public CDPlayer getCdp() {
    return cdp;
}

public void setCdp(CDPlayer cdp) {
    this.cdp = cdp;
}
}

and:

@Component
public class CDPlayer{

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

config:

 @Configuration
 @ComponentScan
 public class CDPlayerConfig {

 }

However, it doesnt work in HelloWorldRestApplication, I get null.

Adding @ContextConfiguration(classes=CDPlayerConfig.class) doesn't help.

What do I miss?

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
jarosik
  • 4,136
  • 10
  • 36
  • 53
  • 1
    static fields cannot be autowired check http://stackoverflow.com/questions/10938529/why-cant-we-autowire-static-fields-in-spring for explanation – seenukarthi Aug 19 '15 at 10:46
  • I created a POJO in main method and then tried to autowire it's field and it still fails. So removing static doesn't solve the problem – jarosik Aug 19 '15 at 10:53
  • update the post with your latest code – seenukarthi Aug 19 '15 at 10:54
  • When you are creating your own instance how do you think spring is going to autowire things? It doesn't know about it hence no auto wiring... – M. Deinum Aug 19 '15 at 11:10
  • what do you mean it doesn't know? Isn't Autowired and Component annotations enough information to perform auto wiring? Dou you also mean i cant inject a wired bean into POJO? – jarosik Aug 19 '15 at 11:17
  • No you are creating an instance yourself... You should use a spring managed instance. – M. Deinum Aug 19 '15 at 11:23

1 Answers1

0

Try enabling @ComponentScan your packages in your main class and get Performer class instance from ApplicationContext as below:

@SpringBootApplication
@RestController
@ComponentScan({“package.name.1”,”package.name.2”})
public class HelloWorldRestApplication {

public static void main(String[] args) {
    ApplicationContext ctx = SpringApplication.run(HelloWorldRestApplication.class, args);

    Performer p = ctx.getBean(Performer.class);//get the bean by type                      
    p.perform();
    }
}
Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108