Spring注释@Inject不起作用

时间:2013-05-20 12:20:34

标签: java spring

我让代码@Inject在一个类中工作,但在其他类中不起作用。 这是我的代码:

  • 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包中存在

com.myfashions.dao类。 @Inject在Seller.java中无效。有什么理由吗?

3 个答案:

答案 0 :(得分:7)

确保为组件扫描注释了SellerRetrieverUserDAO的实现。这将确保后者注入前者:

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

使用UserDAO注释@Component实施。

扫描多条路径时使用:

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

答案 1 :(得分:3)

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

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

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

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

您可以在下面看到我的评论,说明保留@Autowired而不是@Inject的一个很好的理由。

答案 2 :(得分:2)

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

相关问题