Spring dependency injection not working spring 4

2019-09-21 20:54发布

问题:

Im trying to inject my object , however it throws null pointer exception . Please advise. I have tried to pass the resource name as both capital and small letter, However still throw same error.

017-01-19T23:17:31.364+0800|Info: java.lang.NullPointerException
       at com.vinoth.test.AppMain.mainMethod(AppMain.java:8)
       at com.vinoth.test.HelloController.byParameter(HelloController.java:30)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
       at java.lang.reflect.Method.invoke(Method.java:498)
       at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)

Below is my component class .

 @Component
public class Processor {

public int sum(int a , int b){
    return a+b;
}

}

Error is at line : int value = processor.sum(1, 2);

public class AppMain {
@Resource(name="Processor")
Processor processor;

public int mainMethod() {

    int value = processor.sum(1, 2);
    return value;
}

}

Here is my AppConfig class

   @Configuration
   @EnableWebMvc
   @ComponentScan(basePackages = "com.vinoth.test")
   public class AppConfig extends WebMvcConfigurerAdapter {
   @Bean
   public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new  InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

@Override
  public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("home");
    registry.addStatusController("/detail", HttpStatus.BAD_REQUEST);  
  }

@Override
public void    configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)    {
    configurer.enable();
}

 }

回答1:

You haven't specified bean name for your component so it's got default name which in your case is processor, not Processor as you stated in @Resource annotation.

The convention is to use the standard Java convention for instance field names when naming beans. That is, bean names start with a lowercase letter, and are camel-cased from then on. Examples of such names would be (without quotes) 'accountManager', 'accountService', 'userDao', 'loginController', and so forth.

Read more here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-beanname

If my advice hasn't helped try to use @Autowired or @Inject annotation instead. In case of multiple beans of the same type use @Qualifier to specify which one should be used.