Spring 注释@Inject不起作用



我的代码@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中不工作。有什么原因吗?

确保为组件扫描对SellerRetrieverUserDAO的实现都进行了注释。这将确保后者被注入到前者中:

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

@Component注释UserDAO的实现。

扫描多条路径时使用:

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

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

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

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

在Spring框架中@Inject和@Autowired有什么区别?在什么情况下使用哪一种?

,你可以在下面看到我的评论,解释了保留@Autowired而不是@Inject的一个很好的理由。

我发现我的错误,我张贴这是因为以防有人有同样的问题。我使用new操作符创建SellerRetriver对象。如果使用new操作符调用特定的类,则Inject将不起作用。

最新更新