开发者

Spring MVC Dependency Injection not working in object called from within RequestMappingController

开发者 https://www.devze.com 2023-02-16 07:19 出处:网络
When I try to do like below and I have a RequestMapping controller class within Spring MVC that instantiates and calls an external class, I am unable to use dependency injection within that class, suc

When I try to do like below and I have a RequestMapping controller class within Spring MVC that instantiates and calls an external class, I am unable to use dependency injection within that class, such a开发者_运维问答s if I try to use

@Resource(name = "savedsearchesService")
        private SavedSearchesService savedsearchesService;

I get a nullpointer exception. Instead I have to pass SavedSearchesService savedsearchesService from my controller method into the other external method to get it to work.

I'm wondering if anyone can point out why it is this way as I am curious and if there is something I am missing as far as how to do this properly. Thanks

@Controller
@RequestMapping("")
public class MainController {

    @Resource(name = "savedsearchesService")
    private SavedSearchesService savedsearchesService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getPersons(Model model, HttpServletRequest request)
            throws IOException {

        HttpSession session = request.getSession();


        SomeExternalClass someExternalClass = new SomeExternalClass ();
        someExternalClass.Main();
    }

}

Here is the example of the external classs:

public class SomeExternalClass {

    @Resource(name = "savedsearchesService")
    private SavedSearchesService savedsearchesService;

    public void Main () {
        savedsearchesService.get();

    }
}


The problem is with this line:

SomeExternalClass someExternalClass = new SomeExternalClass();

All classes which depends on springs dependency injection must be spring managed, which is not the case whenever you instantiate classes with the new keyword.

There are several alternatives. To mention some:

  • Inject SomeExternalClass into your controller.

  • Create a spring-managed factory which hides instantiation logic (such as applicationContext.getBean())

0

精彩评论

暂无评论...
验证码 换一张
取 消