Java – Spring annotation @Inject doesn’t work

javaspring

I have the code @Inject works in one class but not in other.
Here's my code:

  • context.xml
<?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.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context.xsd
                    ">
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <context:component-scan base-package="com.myfashions.services"/>
    <context:component-scan base-package="com.myfashions.dao"/>
</beans>
  • SellerRetriever.java
public class SellerRetriever {
    @Inject
    UserDAO userDAO;
    ...
    ...
}

UserDAO class is present in com.myfashions.dao package.
@Inject is not working in Seller.java. Any reason why?

Best Solution

Make sure that both SellerRetriever and the implementation of UserDAO are annotated for the component scan. This will ensure that the latter is injected into the former:

@Service
public class SellerRetriever {
    @Inject
    UserDAO userDAO;
    ...
}

Annotate the UserDAO implementation with @Component.

When scanning multiple paths use:

<context:component-scan base-package="com.myfashions.services, com.myfashions.dao"/>