vicky
vicky

Reputation: 1046

Spring annotation @Inject doesn't work

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

<?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>
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?

Upvotes: 5

Views: 13047

Answers (3)

vicky
vicky

Reputation: 1046

I found my mistake, I'm posting this because in case anyone has the same problem. I used new operator to create an SellerRetriver object. Inject won't work if new operator is used to call that particular class.

Upvotes: 3

Mik378
Mik378

Reputation: 22191

To be eligible to scan, your class must be annotated with either a more generic @Component, or @Service or @Repositories etc.. In your case, @Service logically better fits. You could then (if you need) define some aspects (AOP) focused specifically on services call.

Besides, you may want to use @Autowired instead of @Inject to retrieve your bean.

For more information about differences concerning these two annotations:

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

and you can see my comment just below explaining one good reason to keep @Autowired instead of @Inject.

Upvotes: 3

Reimeus
Reimeus

Reputation: 159874

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"/>

Upvotes: 7

Related Questions