我在一个 Spring Boot 项目中有几个类,一些使用 @Autowired,一些不使用。我的代码如下:
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,但当我尝试访问它时我的应用程序因空指针异常而中断。
我已经在这里阅读了很多主题并进行了谷歌搜索,但还没有找到解决方案。我已尽力提供所有必要信息,如有遗漏请告知我。
最佳答案
我猜你在 Autowiring 发生之前调用了 init()
。用@PostConstruct 注释 init()
使其在所有 spring Autowiring 之后自动调用。
编辑:看到您的评论后,我猜您正在使用 new MyServiceImpl()
创建它。这会从 Spring 手中夺走 MyServiceImpl 的控制权,并将其交给您。在这种情况下 Autowiring 将不起作用
关于java - Spring Boot Autowiring null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26461697/