簡體   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