我在Spring Boot項目中有幾個類,有些使用@Autowired,有些不使用。在這裏我的代碼如下:Spring Boot Autowired null
Application.java(@Autowired作品):
package com.example.myproject;
@ComponentScan(basePackages = {"com.example.myproject"})
@Configuration
@EnableAutoConfiguration
@EnableJpaRepositories(basePackages = "com.example.myproject.repository")
@PropertySource({"classpath:db.properties", "classpath:soap.properties"})
public class Application {
@Autowired
private Environment environment;
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public SOAPConfiguration soapConfiguration() {
SOAPConfiguration SOAPConfiguration = new SOAPConfiguration();
SOAPConfiguration.setUsername(environment.getProperty("SOAP.username"));
SOAPConfiguration.setPassword(environment.getProperty("SOAP.password"));
SOAPConfiguration.setUrl(environment.getProperty("SOAP.root"));
return SOAPConfiguration;
}
的HomeController(@Autowired作品):
package com.example.myproject.controller;
@Controller
class HomeController {
@Resource
MyRepository myRepository;
爲MyService(@Autowired不工作):
package com.example.myproject.service;
@Service
public class MyServiceImpl implements MyService {
@Autowired
public SOAPConfiguration soapConfiguration; // is null
private void init() {
log = LogFactory.getLog(MyServiceImpl.class);
log.info("starting init, soapConfiguration: " + soapConfiguration);
url = soapConfiguration.getUrl(); // booom -> NullPointerException
我沒有得到SOAPConfiguration,但我的應用程序打破空指針異常,當我嘗試訪問它。
我已經在這裏閱讀了許多主題,並且搜索了一些內容,但是還沒有找到解決方案。我試圖提供所有必要的信息,請讓我知道是否有遺漏。
從哪裏調用'init'方法?我懷疑構造函數。 – 2014-10-20 08:49:23
log.info打印:啓動init,soapConfiguration:null – dexBerlin 2014-10-20 08:51:18
HomeController.update創建一個新的MyServiceImpl並調用myService.update,它調用它的init方法。 – dexBerlin 2014-10-20 08:53:36