Spring boot autowired null

I have several classes in the Spring boot project, some work with @Autowired, some do not. Here is my code:

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 not working):

 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 am not getting SOAPConfiguration, but my application crashes with an exceptional exception when I try to access it.

I already read a lot of topics here and searched Google, but have not yet found a solution. I tried to provide all the necessary information, please let me know if something is missing.

+6
source share
2 answers

I think you call init() before the auto-install happens. Annotate init() with @PostConstruct so that it is automatically called after autwiring spring.

EDIT: after looking at your comment, I think you create it using new MyServiceImpl() . This takes control of MyServiceImpl from spring and gives it to you. Autowiring will not work in this case

+8
source

Did you create a bean for the SOAPConfiguration class in any of the configuration classes? If you want to use the autwire class in your project, you need to create a bean for it. For instance,

 @Configuration public class SomeConfiguration{ @Bean public SOAPConfiguration createSOAPConfiguration(){ return new SOAPConfiguration(); } } public class SomeOtherClass{ @Autowired private SOAPConfiguration soapConfiguration; } 
+1
source

Source: https://habr.com/ru/post/976964/


All Articles