Spring Boot Autowired null
Solution 1
I guess you call init()
before the autowiring takes place. Annotate init()
with @PostConstruct to make it call automatically after all the spring autowiring.
EDIT: after seeing your comment, I guess you are creating it using new MyServiceImpl()
. This takes away the control of the MyServiceImpl from Spring and gives it to you. Autowiring won't work in those case
Solution 2
Did you created a bean for the class SOAPConfiguration in any of your configuration classes? If you want to autowire a class in your project, you need to create a bean for it. For example,
@Configuration
public class SomeConfiguration{
@Bean
public SOAPConfiguration createSOAPConfiguration(){
return new SOAPConfiguration();
}
}
public class SomeOtherClass{
@Autowired
private SOAPConfiguration soapConfiguration;
}
Comments
-
dexBerlin almost 2 years
I have several classes in a Spring Boot project, some work with @Autowired, some do not. Here my code follows:
Application.java (@Autowired works):
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 works):
package com.example.myproject.controller; @Controller class HomeController { @Resource MyRepository myRepository;
MyService (@Autowired does not work):
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
I do not get the SOAPConfiguration but my application breaks with a null pointer exception when I try to access it.
I have already read many Threads here and googled around, but did not find a solution yet. I tried to deliver all necessary information, please let me know if anything misses.
-
dexBerlin over 9 yearsThe Application.java should do that? As in my explanation?
-
dexBerlin over 9 yearsI added the @PostContruct annotation, but soapConfiguration is still null.
-
furkan3ayraktar over 9 yearsAre you sure the method on your Application.java called for SOAPConfiguration?