简体   繁体   中英

Spring - Inject bean using Autowire

I'm trying to inject a bean in a simple java project but I'm getting a NullPointerException for ProductInformationServiceImpl.

These are the classes I'm using:

AppConfig.java (Spring configuration class)

package com.test.testing.config;

@Configuration
@ComponentScan(basePackages = "com.test")
public class AppConfig {
}

TestService.java interface:

package com.test.testing.service;

public interface TestService {
    String doIt();
}

TestService.java implementation:

package com.test.testing.service;

@Service
public class TestServiceImpl implements TestService {
    public String doIt() {
        return "you did it!";
    }
}

Main class:

package com.test.testing;

public class App {
    public static void main( String[] args ){
        Test w = new Test();
        System.out.println(w.getTestService().doIt());
    }
}

class Test {
    @Autowired
    private TestService testServiceImpl;

    public TestService getTestService() {
        return testServiceImpl;
    }

    public void setTestService(TestService testServiceImpl) {
        this.testServiceImpl = testServiceImpl;
    }
}

I did some tests retrieving the bean using:

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
TestService app = (TestService)context.getBean("testServiceImpl");

But that is something I'd like to avoid.

I found that the general suggestion id to use constructor injection instead of field injection, that helps you a lot with the testability.

@Component
@RequiredArgsConstructor(onConstructor=@__(@Autowired))
public class Animal {
    private final Sound sound;
    public String makeSound() {
        return sound.make();
    }
}

In the test you can pass the mocks or whatever in the constructor, while when you run your application the constructor injection will be taken care of automatically. Here's a tiny test app which a showcase of the constructor injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM