简体   繁体   中英

Spring annotation @Inject doesn't work

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?

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM