Spring注入在不同的服务类中不起作用 [英] Spring Injection not working in different service class
问题描述
我有课
@Service("registrationService")
@Transactional
public class RegistrationService {
@Resource(name="registrationDAO")
public RegistrationDAO registrationDAO;
在控制器中,我可以毫无问题地访问 registrationService 和 registrationDAO.
In the Controller i can access registrationService and registrationDAO with no problem.
我还有一堂课
@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";
}
现在,如果我在控制器中调用测试函数,那么它会在 registrationDAO 上给出空指针异常
Now if i call test function in controller then it gives null pointer exception on registrationDAO
推荐答案
All your @Service
, @Repository
, @Controller
, @Component
(等)注解类必须由弹簧管理才能自动装配工作.确保它们被 spring 类路径扫描:
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" />
在某些情况下,@Autowire
按类型进行自动装配,可用于避免使用 @Resource提供的
name
参数代码>.
In some cases @Autowire
, which does autowiring by type, can be useful to avoid the name
argument you're supplying with the @Resource
.
这篇关于Spring注入在不同的服务类中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!