5

我的代码@Inject在一个类中有效,但在其他类中无效。这是我的代码:

  • 上下文.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类存在于com.myfashions.dao包中。 @Inject不在 Seller.java 中工作。有什么理由吗?

4

3 回答 3

7

确保为组件扫描注释了两者SellerRetriever和实现。UserDAO这将确保后者被注入到前者中:

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

用注释UserDAO实现@Component

扫描多条路径时使用:

<context:component-scan base-package="com.myfashions.services, com.myfashions.dao"/>
于 2013-05-20T12:32:03.853 回答
3

为了有资格扫描,您的类必须使用更通用@Component的或@Service@Repositories等进行注释。在您的情况下,@Service逻辑上更适合。然后,您可以(如果需要)定义一些专门针对服务调用的方面 (AOP)。

此外,您可能希望使用@Autowired而不是@Inject检索您的 bean。

有关这两个注释的差异的更多信息:

Spring Framework 中的@Inject 和@Autowired 有什么区别?在什么条件下使用哪一种?

您可以在下面看到我的评论,解释了保留@Autowired而不是@Inject.

于 2013-05-20T12:22:41.637 回答
2

我发现我的错误,我发布这个是因为以防万一有人遇到同样的问题。我使用 new 运算符创建了一个 SellerRetriver 对象。如果使用 new 运算符调用该特定类,则注入将不起作用。

于 2013-05-28T06:24:27.843 回答