spring - Unable to autowire attributes in package -


for reason, in config package, can not autowire fields while in controller package, there not seem problem.

for instance:

servlet-context.xml

<context:component-scan base-package="service, controller, config" /> 

root-context.xml (tried adding service here well)

<context:component-scan base-package="security" /> 

this not work: setup class inside config package. receive null pointer error.

@component public class setup { //inside config package     @autowired     private userservice userservice; //null pointer error     /*..other stuff */ } 

this work: controller inside controller package:

@controller @requestmapping(value="/contact") public class contactcontroller { //inside controller package     @autowired     private userservice userservice; //this works     /*..other stuff..*/ } 

why work controller package not config package?

this happens because @service class userservice not visible in of 2 packages "config" or "controller" assume need component scan packages containing services:

<context:component-scan base-package="service" /> 

edit:

usually should remember if bean/component not within scanned context null on injection (autowiring).

edit 2:

so you've seen spring has 2 type of contexts, applicationcontext , servletcontext. if scan bean in servletcontext accessible controllers (or name states servlets), beans scanned applicationcontext accessible services or other components , servlet can access beans scanned here without having scan them in servlet context.

in case should have following setup:

in servlet-context.xml:

<context:component-scan base-package="controller" /> 

in applicationcontext.xml or root-context.xml (i assume you've referenced in web.xml)

<context:component-scan base-package="config, security, services" /> 

the image bellow illustrates context hierarchy spring:

enter image description here


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -