ssh2 依赖注入的问题,通过spring将dao注入service,但在action中不通过注入,而是直接new,结果失败。

action-->service-->dao.按照这样的顺序依赖注入,是成功的。我现在进行修改,在action中不进行注入,直接new一个service对象出来,结果在service类中,dao对象注入失败。请大位大虾帮忙解决下。

你new出来的service对象和你在spring中注入的service对象不是同一个对象,在spring中service对象到你是赋了值的,但是你new出来的service对象中的dao是没有赋值的。当然会出问题,你要么就全部注入,不要new ,在实际开发中也不会这样做
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-08-20

可以不需要New,也不需要注解。你可以在需求的时候,创建实例时,从Spring中把它的实现取出来即可。


比如:


    

UserService us = SpringContextUtils.getBean("userServiceImpl");

UserServiceImpl中的DAO是自动注入的。

而不用是 UserService us = new UserServiceImpl();

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextUtils implements ApplicationContextAware {

private static ApplicationContext applicationContext;

        @Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}

public static ApplicationContext getApplicationContext() {
return applicationContext;
}

@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
if (applicationContext == null){
                    return null;
                }
return (T)applicationContext.getBean(name); 
}
}

第2个回答  2013-08-20

楼主你在web.xml里面一定配好了listener对吧,那你直接这样写

ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
ctx.getBean("YourDAOBeanName");

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网