问题
I have class
@Service("registrationService")
@Transactional
public class RegistrationService {
@Resource(name="registrationDAO")
public RegistrationDAO registrationDAO;
In the Controller i can access registrationService and registrationDAO with no problem.
I have another class
@Service("securityService")
public class SecurityService implements UserDetailsService {
protected static Logger logger = Logger.getLogger("service");
@Resource(name="registrationDAO")
public RegistrationDAO registrationDAO;
public String test(){
logger.debug(registrationDAO.findUserByID(1) );
return "Testing";
}
Now if i call test function in controller then it gives null pointer exception on registrationDAO
回答1:
All your @Service
, @Repository
, @Controller
, @Component
(etc.) annotated class must be spring-managed for autowiring to work. Make sure they are picked up by spring classpath scanning:
<context:component-scan base-package="com.company" />
In some cases @Autowire
, which does autowiring by type, can be useful to avoid the name
argument you're supplying with the @Resource
.
来源:https://stackoverflow.com/questions/5437331/spring-injection-not-working-in-different-service-class