【发布时间】:2017-12-04 09:43:06
【问题描述】:
我正在尝试在服务器启动时加载属性数据。为此,我创建了一个实现ServletContextListener 的类。这将加载所有属性。
在我的 DaoImpl 类中,我试图获取属性数据并初始化为一些字符串。但它会抛出异常
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'bbService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bbService': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BBDAO' defined in ServletContext resource [/WEB-INF/spring-web-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.bb.dao.BBDaoImpl]: Constructor threw exception; nested exception is java.lang.NullPointerException
这是我的配置类
public class Config implements ServletContextListener {
private static final String ATTRIBUTE_NAME = "config";
private Properties config = new Properties();
@Override
public void contextInitialized(ServletContextEvent event){
try {
Resource resource = new ClassPathResource("/uat.properties");
config = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
try {
throw new QiibException("Loading config failed");
} catch (QiibException e1) {
e1.printStackTrace();
}
}
event.getServletContext().setAttribute(ATTRIBUTE_NAME, this);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
}
public static Config getInstance(ServletContext context) {
return (Config) context.getAttribute(ATTRIBUTE_NAME);
}
public String getProperty(String key) {
return config.getProperty(key);
}
}
DAOImpl 类是
public class BBDaoImpl extends JdbcDaoSupport implements BBDao, ServletContextAware {
Properties properties = null;
@Autowired
private ServletContext ctx;
public void setServletContext(ServletContext servletContext) {
this.ctx = servletContext;
}
public BBDaoImpl() throws IOException {
super();
Config config = Config.getInstance(ctx); --> ctx is null here.
这里有什么问题?
任何想法将不胜感激。
【问题讨论】:
-
没错,怎么可能是其他方式。 1) 你创建对象 => 构造函数调用 2) 因为你有
ServletContextAware你得到了setServletContext调用的上下文。基本上你不能在没有对象实例的情况下设置上下文,所以构造函数调用总是首先出现 -
将
@Repository注释放在你的BBDaoImpl类上。 -
@SandipSolanki,它抛出 org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.qiib.dao.BBDAo' available: expected single matching bean but found 2: BBDaoImpl,BBDAO .. 我已经有
-
@varren,如何解决这个问题?
-
为什么?为什么要将 DB 层与 Web 层联系起来(这就是您正在有效地做的事情)。而是使用 Spring 使用
@PropertySource加载属性文件并使用@Value或Environment类来访问属性。
标签: java spring servlets servletcontextlistener