繁体   English   中英

春季-使用Autowire注入bean

[英]Spring - Inject bean using Autowire

我试图在一个简单的Java项目中注入一个bean,但是我得到了ProductInformationServiceImpl的NullPointerException。

这些是我正在使用的类:

AppConfig.java(Spring配置类)

package com.test.testing.config;

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

TestService.java接口:

package com.test.testing.service;

public interface TestService {
    String doIt();
}

TestService.java实现:

package com.test.testing.service;

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

主班:

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;
    }
}

我使用以下方法进行了一些检索bean的测试:

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

但这是我要避免的事情。

我发现一般建议ID使用构造函数注入而不是字段注入,这对可测试性有很大帮助。

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

在测试中,您可以传递模拟或构造函数中的任何内容,而在您运行应用程序时,构造函数注入将被自动处理。 这是一个微型测试应用程序 ,其中展示了构造函数注入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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