有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在Spring中加载servlet上下文

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

这里怎么了

任何想法都将不胜感激


共 (2) 个答案

  1. # 1 楼答案

    如果查看异常,您会发现服务类中存在嵌套异常,它试图自动连接尚未初始化的DAOBean

    首先看看你的配置:- 1.您正在扫描您的dao Repo。 2.如果是,请在Dao类中放置任何原型(@Component)

    请看看这些,你会在你的异常中找到你的解决方案

  2. # 2 楼答案

    请注意,您只想获取一些属性并初始化类,为什么不以spring的方式实现呢

    1. 将属性放入spring属性文件中,并使BBDaoImpl实现EnvironmentAware接口和InitializingBean接口,然后可以在InitializingBean中声明的afterPropertiesSet方法中初始化BBDaoImpl。关键的过程是实现EnvironmentAware,这样你就可以得到环境对象的引用,通过它你可以得到你的属性
    2. 或者你可以实现ServletConfigAware,它与上面的类似