Spring At least one base package must be specified

2019-06-10 07:43发布

问题:

When I'm compiling my project it gives this error and stop compiling

org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/application-context.xml]; nested exception is java.lang.IllegalArgumentException: At least one base package must be specified

Why this exception happen and How I solve it.

回答1:

As per Spring Doc

Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext. To autodetect these classes and register the corresponding beans requires the inclusion of the following element in XML where 'basePackage' would be a common parent package for the two classes (or alternatively a comma-separated list could be specified that included the parent package of each class).

Hence your application-context should look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">

     <context:component-scan base-package="org.example"/>

</beans>

to enable your package to get scanned via component-scan you should annotate your java class with respective annotation as per the requirement. Like @Controllers or @Service etc. See the full details here.



回答2:

<context:component-scan base-package="Your package">

</context:component-scan>

try adding this in you configuration file



回答3:

From my comments above

The reason could be you have annotation driven context configuration enabled (<context:annotation-config></context:annotation-config>) in you application context, but you have to provided any base package to scan for spring beans.

Add the root package of your application as the base package to scan for bean definitions

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