Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot null pointer exception on org.springframework.beans.factory.UnsatisfiedDependencyException

I am a newbie to spring boot and I have this challenge in my spring boot rest endpoints. I am getting a null exception if I try to use the Autowired component on a field.

Here is the exception I am getting

  org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'homeContoller': Unsatisfied dependency expressed through field 'common'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'common' defined in file Common.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [Common]: Constructor threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:130) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1420) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:405) [spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.11.RELEASE.jar:2.2.11.RELEASE]
        at Application.main(Application.java:23) [classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_172]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_172]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_172]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_172]
        at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.2.11.RELEASE.jar:2.2.11.RELEASE]
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'common' defined in file Common.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [Common]: Constructor threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:313) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:294) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1356) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1203) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1307) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1227) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        ... 24 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [Common]: Constructor threw exception; nested exception is java.lang.NullPointerException
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:309) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        ... 37 common frames omitted
    Caused by: java.lang.NullPointerException: null
        at Common.<init>(Common.java:39) ~[classes/:na]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_172]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_172]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_172]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_172]
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204) ~[spring-beans-5.2.10.RELEASE.jar:5.2.10.RELEASE]
        ... 39 common frames omitted

and here is my java code

  @Component
    public class Common {
    
/* tried this and still not working(does not change locale per request it pick default language)
     @Autowired
public Common(LanguageTranslator translator)
{
   this.translator=translator;
    SUBJECT_EXISTS =translator.translate("SUBJECT_EXISTS");
}
*/
        @Autowired
        LanguageTranslator translator;
    
        public  String SUBJECT_EXISTS =translator.translate("SUBJECT_EXISTS") ;//failing error
    
    }   
    
    @Component
    public class LanguageTranslator {
    
    
        private  ResourceBundleMessageSource messageSource;
    
        @Autowired
        public LanguageTranslator(ResourceBundleMessageSource resourceBundleMessageSource)
        {
            this.messageSource=resourceBundleMessageSource;
        }
    
    
    
        public  String translate(String msg) {
            Locale locale = LocaleContextHolder.getLocale();
            return messageSource.getMessage(msg, null, locale);
        }
    
    
    }
    
    @RestController
    @RequestMapping("/home")
    public class HomeContoller {
    
    
    
        @Autowired
        Common  common;
    
    
        @GetMapping("/")
        public String home() {
    
            return "Home page";
        }
    
        @RequestMapping(value = "/demo", method = RequestMethod.POST)
        public ResponseEntity all_menu_assignment(HttpServletRequest req)  {
    
    
            return  ResponseEntity
                    .ok().body(new ServerResponse(00,common.SUBJECT_EXISTS));
    
        }
    }
like image 650
Nemuga Dev Avatar asked Mar 02 '23 17:03

Nemuga Dev


1 Answers

Take a look at the documentation of @Autowired (in general always try reading the Javadocs to understand how Spring functionality works):

Autowired Fields

Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.

As you can see the field is injected after the Common bean is constructed, while you are trying to use it in a field initializer, before the constructor finishes. You can try constructor injection instead:

public String SUBJECT_EXISTS;

@Autowired
public Common(LanguageTranslator translator) {
    this.translator = translator;
    SUBJECT_EXISTS = translator.translate("SUBJECT_EXISTS");
}

Side note: Naming fields with uppercase is a bad practice in Java, since the field is not final. It should be more like subjectExists.

like image 85
M A Avatar answered Mar 04 '23 05:03

M A