Spring Autowiring Service doesn't work in my Controller

Your configuration is very strange...

First rule out the obvious

I don't see root web application context configuration in your web.xml. Could it be that you forgot to add this piece of code?

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        WEB-INF/app-config.xml
    </param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Now a little bit of theory

Bit of Spring theory - Spring uses application context hierarchy for web applications:

  • top level web application context is loaded by ContextLoaderListener
  • then there are separate contexts for each DispatcherServlet instances

When a new bean is being instantiated, it can get dependencies either from the context where it is being defined or from parent context. This makes possible to define common beans in the root context (services, DAO, ...) and have the request handling beans in servlet application contexts as each servlet can have its own set of controllers, view handers, ...

Last, but not least - your errors

You are configuring MVC in your root context. That is just wrong. Remove the <mvc: context from there.

You are also registering your controllers in the root context via the <context:component-scan> on your base package. Make the component scan just on the services package or separate your classes into two top level packages core (for the root beans) and servlet (for servlet beans).


Make sure that your UserServiceImpl is in same package as defined in context:component-scan. If it's not, spring will not be able to detect it. Also, try removing value attribute from UserServiceImpl definition, since there is only 1 bean of that type. Spring will be able to autowire it by type.