0

My project structure is:-

Java Resources

src
    com.pizzeria.config
     AppConfig.java
     MySpringDispatcherServletInitializer.java

WebContent

META-INF
    MANIFEST.MF
WEB-INF
    lib
    view
        welcome.jsp

Contents of my AppConfig.java file

package com.pizzeria.config;

import java.util.Properties;
import java.util.logging.Logger;

import javax.persistence.EntityManagerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("com.pizzeria.*")
@PropertySource("classpath:*.properties")
@EnableTransactionManagement
public class AppConfig {

    @Autowired
    private Environment env;

    // set up a logger for diagnostics

        private Logger logger = Logger.getLogger(getClass().getName());

    // define a bean for ViewResolver

        @Bean
        public ViewResolver viewResolver() {

            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

            viewResolver.setPrefix("/WEB-INF/view/");
            viewResolver.setSuffix(".jsp");

            return viewResolver;
        }


         @Bean
           public PlatformTransactionManager transactionManager(
             EntityManagerFactory emf){
               JpaTransactionManager transactionManager = new JpaTransactionManager();
               transactionManager.setEntityManagerFactory(emf);
               return transactionManager;
           }

        @Bean
        public LocalContainerEntityManagerFactoryBean localEntityManagerFactory() {
            LocalContainerEntityManagerFactoryBean localEntityManagerFactory = new LocalContainerEntityManagerFactoryBean();
            localEntityManagerFactory.setDataSource(dataSource());
            localEntityManagerFactory.setPackagesToScan("com.pizzeria");
            localEntityManagerFactory.setJpaVendorAdapter(hibernateJpaVendorAdapter());
            localEntityManagerFactory.setJpaProperties(additionalProperties());
            return localEntityManagerFactory;
        }

        @Bean
        public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {
            HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
            return hibernateJpaVendorAdapter;
        }

        Properties additionalProperties() {
               Properties properties = new Properties();
               properties.setProperty("hibernate.hbm2ddl.auto",
                                        env.getProperty("hibernate.hbm2ddl.auto"));
               properties.setProperty("hibernate.dialect", 
                                        env.getProperty("hibernate.dialect"));
               properties.setProperty("hibernate.cache.use_second_level_cache", 
                                        env.getProperty("hibernate.cache.use_second_level_cache"));
               properties.setProperty("hibernate.cache.use_query_cache", 
                                        env.getProperty("hibernate.cache.use_query_cache"));
               properties.setProperty("hibernate.show_sql",
                                        env.getProperty("hibernate.show_sql"));
               properties.setProperty("hibernate.format_sql", 
                                        env.getProperty("hibernate.format_sql"));

               return properties;
           }

        @Bean
        public DriverManagerDataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();

            dataSource.setDriverClassName(env.getProperty("jdbc.driver"));
            dataSource.setUrl(env.getProperty("jdbc.url"));
            dataSource.setUsername(env.getProperty("jdbc.user"));
            dataSource.setPassword(env.getProperty("jdbc.password"));
            return dataSource;
        }
}

Contents of my DispatcherServetInitializer

package com.pizzeria.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MySpringDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class [] {AppConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String [] {"/"};
    }



}

The error which i'm getting while running my application on tomcat :-

19-Aug-2018 20:13:37.805 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 3 Spring WebApplicationInitializers detected on classpath
19-Aug-2018 20:13:37.936 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
19-Aug-2018 20:13:38.055 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
 org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:223)
    at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:194)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)
    at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:133)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:620)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:521)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4790)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5256)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:180)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
    ... 25 more

19-Aug-2018 20:13:38.078 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
19-Aug-2018 20:13:38.085 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStop Exception sending context destroyed event to listener instance of class [org.springframework.web.context.ContextLoaderListener]
 java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
    at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:176)
    at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1037)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1013)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:963)
    at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:525)
    at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:112)
    at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4837)
    at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5478)
    at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:226)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:985)
    at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

How can I fix this error? I searched a lot about it but everywhere they are saying to use @EnableWebMvc on the configuration class. I already have it in my config class.But still don't know why container is looking for applicationContext.xml. Can anyone help me to get rid out of this error

I'm using spring-webmvc 5 version and i also deleted web.xml file from my tomcat

1 Answers1

0

The root configuration is required, the servlet configuration is optional.

To fix: Move new Class [] {AppConfig.class} to getRootConfigClasses().

As documented in the javadoc of AbstractAnnotationConfigDispatcherServletInitializer:

Implementations are required to implement:

  • getRootConfigClasses() -- for "root" application context (non-web infrastructure) configuration.
  • getServletConfigClasses() -- for DispatcherServlet application context (Spring MVC infrastructure) configuration.

If an application context hierarchy is not required, applications may return all configuration via getRootConfigClasses() and return null from getServletConfigClasses().

See also StackOverflow question getServletConfigClasses() vs getRootConfigClasses()` when extending AbstractAnnotationConfigDispatcherServletInitializer.

Community
  • 1
  • 1
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • still there's same problem even after moving AppConfig.class to rootConfiguration . Don't know what's going wrong? – Shailendra Chauhan Aug 20 '18 at 08:24
  • this is the error i'm getting after changing things:- 20-Aug-2018 14:04:49.701 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class [org.springframework.web.context.ContextLoaderListener] java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml! – Shailendra Chauhan Aug 20 '18 at 08:39
  • That is a different error, so not "same problem". As your current issue has been fixed, and you're on to the next issue, create a new question showing your updated code and the new stacktrace. – Andreas Aug 20 '18 at 16:36
  • yes friend i've updated the code and posted u can refer below link https://stackoverflow.com/questions/51942336/dispatcherservlet-is-not-able-to-locate-config-class – Shailendra Chauhan Aug 21 '18 at 05:52
  • I thought you said you got a different error when you moved AppConfig.class to rootConfiguration. – Andreas Aug 21 '18 at 15:46