Reputation: 447
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.
Upvotes: 10
Views: 35841
Reputation: 543
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;
}
Upvotes: 2
Reputation: 2604
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
Upvotes: 12