Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to load ApplicationContext (with annotation)

Tags:

This is my class for test.

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) public class UserServiceImplIT {      @Autowired     private SampleService sampleService;       @BeforeClass     public static void setUp() {         System.out.println("-----> SETUP <-----");     }      @Test     public void testSampleService() {         assertTrue(true);     } }       

exception (many exceptions, main : Failed to load ApplicationContext,
Error creating bean with name 'defaultServletHandlerMapping'.
Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception;,
A ServletContext is required to configure default servlet handling )

java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)

AppConfig - basic configuration file.

@Configuration @ComponentScan("ru.moneymanager.web") @EnableWebMvc @EnableTransactionManagement @PropertySource(value = {"classpath:application.properties"}) @Import({SecurityConfig.class,}) public class AppConfig {      @Bean     public SampleService getSampleService() {         return new SampleServiceImpl();     }      @Bean     public InternalResourceViewResolver setupViewResolver() {         InternalResourceViewResolver resolver = new InternalResourceViewResolver();         resolver.setPrefix("/WEB-INF/pages/");         resolver.setSuffix(".jsp");         resolver.setViewClass(JstlView.class);          return resolver;     }      @Autowired     private Environment environment;      @Bean     public LocalSessionFactoryBean sessionFactory() {         LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();         sessionFactory.setDataSource(dataSource());         sessionFactory.setPackagesToScan(new String[]{"ru.moneymanager.web"});         sessionFactory.setHibernateProperties(hibernateProperties());         return sessionFactory;     }      @Bean     public DataSource dataSource() {         DriverManagerDataSource dataSource = new DriverManagerDataSource();         dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));         dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));         dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));         dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));         return dataSource;     }      private Properties hibernateProperties() {         Properties properties = new Properties();         properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));         properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));         properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));         properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));         return properties;     }      @Bean     @Autowired     public HibernateTransactionManager transactionManager(SessionFactory s) {         HibernateTransactionManager txManager = new HibernateTransactionManager();         txManager.setSessionFactory(s);         return txManager;     } }        

SecurityConfig

@Configuration @ComponentScan("ru.moneymanager.web") @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled=true) public class SecurityConfig extends WebSecurityConfigurerAdapter {     @Autowired     AuthenticationService authenticationService;     @Override     protected void configure(HttpSecurity http) throws Exception {         CharacterEncodingFilter filter = new CharacterEncodingFilter();         filter.setEncoding("UTF-8");         filter.setForceEncoding(true);         // отключена защита csrf на время тестов         http.csrf().disable().addFilterBefore(filter,CsrfFilter.class);         http.authorizeRequests().antMatchers("/account/**").hasRole("USER")             .antMatchers("/user/**").hasRole("ADMIN")             .and().formLogin();     }     @Autowired     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {         auth.userDetailsService(authenticationService);     }    }        

other configuration files config
this project in git project
tell me, what's wrong? Why the error?

like image 990
makson Avatar asked Apr 09 '16 16:04

makson


People also ask

Can we use ApplicationContext in spring boot?

ApplicationContext is a corner stone of a Spring Boot application. It represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

What is an ApplicationContext?

ApplicationContext is the sub-interface of BeanFactory. BeanFactory provides basic functionalities and is recommended to use for lightweight applications like mobile and applets.

What is @ContextConfiguration in spring?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.

What is SpringJUnitConfig?

@SpringJUnitConfig is a composed annotation that combines @ExtendWith(SpringExtension. class) from JUnit Jupiter with @ContextConfiguration from the Spring TestContext Framework. As of Spring Framework 5.3, this annotation will effectively be inherited from an enclosing test class by default.


2 Answers

Your test requires a ServletContext: add @WebIntegrationTest

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class) @WebIntegrationTest public class UserServiceImplIT 

...or look here for other options: https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html

UPDATE In Spring Boot 1.4.x and above @WebIntegrationTest is no longer preferred. @SpringBootTest or @WebMvcTest

like image 67
ndrone Avatar answered Sep 29 '22 09:09

ndrone


In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class 

Here abc.class was the class that was being tested

like image 34
Ram Avatar answered Sep 29 '22 07:09

Ram