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?
@Inject and @Autowired both annotations are used for autowiring in your application. @Inject annotation is part of Java CDI which was introduced in Java 6, whereas @Autowire annotation is part of spring framework. Both annotations fulfill same purpose therefore, anything of these we can use in our application.
Injectable constructors are annotated with @Inject and accept zero or more dependencies as arguments. @Inject can apply to at most one constructor per class. @Inject is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors.
The behaviour of the @Autowired annotation is similar to the @Inject annotation. The only difference is that the @Autowired annotation is part of the Spring framework. This annotation has the same execution paths as the @Inject annotation, listed in order of precedence: Match by Type.
There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With