Spring注入不适用于不同的服务类
我
@Service("registrationService")
@Transactional
public class RegistrationService {
@Resource(name="registrationDAO")
public RegistrationDAO registrationDAO;
在控制器中有类,我可以毫无问题地访问registrationService和registrationDAO。
我有另一个类
@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上给出空指针异常
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你所有的
@Service
、@Repository
、@Controller
、@Component
(等等)注释的类都必须是spring - 管理自动装配工作。确保它们被 spring 类路径扫描拾取:在某些情况下,按类型自动装配的 @Autowire 可以有效避免您提供的 name 参数
@Resource
。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:In some cases
@Autowire
, which does autowiring by type, can be useful to avoid thename
argument you're supplying with the@Resource
.