无法在Spring中加载servlet上下文

时间:2017-12-04 09:43:06

标签: java spring servlets servletcontextlistener

我正在尝试在服务器启动时加载属性数据。为此,我创建了一个实现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

这是我的Config类

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. 

这里有什么问题?

任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:0)

如果查看异常,您会发现服务类中存在嵌套异常,它尝试自动装入仍未初始化的dao bean。

首先看看你的配置: - 你正在扫描你的道路回购。 2.如果是,则在你的Dao类中放置任何刻板印象(@Component)。

请查看这些内容,您将在异常中找到解决方案。

答案 1 :(得分:0)

注意到你只想获得一些属性并初始化你的课程,为什么不以春天的方式实现这一目标

  1. 将您的属性放在spring属性文件中,并使BBDaoImpl实现EnvironmentAware接口和InitializingBean接口,然后您可以在声明的BBDaoImpl方法中初始化afterPropertiesSetInitializingBean中。关键流程是实施EnvironmentAware,因此您可以获得环境对象的引用,通过它可以获取您的属性
  2. 或者您可以实施ServletConfigAware,它与上述
  3. 类似