[英]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. 我试图在一个简单的Java项目中注入一个bean,但是我得到了ProductInformationServiceImpl的NullPointerException。
These are the classes I'm using: 这些是我正在使用的类:
AppConfig.java (Spring configuration class) AppConfig.java(Spring配置类)
package com.test.testing.config;
@Configuration
@ComponentScan(basePackages = "com.test")
public class AppConfig {
}
TestService.java interface: TestService.java接口:
package com.test.testing.service;
public interface TestService {
String doIt();
}
TestService.java implementation: TestService.java实现:
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: 我使用以下方法进行了一些检索bean的测试:
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. 我发现一般建议ID使用构造函数注入而不是字段注入,这对可测试性有很大帮助。
@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. 这是一个微型测试应用程序 ,其中展示了构造函数注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.