无法加载ApplicationContext(带注释)

时间:2016-04-09 16:00:38

标签: spring spring-mvc junit spring-security

这是我的考试班。

 @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);
}
  }      

异常(很多例外,主要:  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:无法加载ApplicationContext       at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)       at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)       在org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)       在org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)       在org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner $ 1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)       在org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)       在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:290)       在org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:71)       在org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)       在org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:58)       在org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:268)       在org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)       在org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)       在org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)       在org.junit.runners.ParentRunner.run(ParentRunner.java:363)       在org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)       在org.junit.runner.JUnitCore.run(JUnitCore.java:137)       at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)       在com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)       在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)       在java.lang.reflect.Method.invoke(Method.java:491)       在com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)   引起:org.springframework.beans.factory.BeanCreationException:创建名称为&#39; defaultServletHandlerMapping&#39;在类org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration中定义:通过工厂方法的Bean实例化失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.springframework.web.servlet.HandlerMapping]:工厂方法&#39; defaultServletHandlerMapping&#39;抛出异常;嵌套异常是java.lang.IllegalArgumentException:需要ServletContext来配置默认的servlet处理       在org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)       在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)       at org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:306)       在org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)       在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)       在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)

AppConfig - 基本配置文件。

@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);
}   
   }       

其他配置文件config
这个项目在git project中 告诉我,有什么不对?为什么会出错?

3 个答案:

答案 0 :(得分:14)

您的测试需要ServletContext:添加@WebIntegrationTest

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

...或者在此处查看其他选项:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

<强>更新 在Spring Boot 1.4.x及更高版本@WebIntegrationTest不再是首选。 @SpringBootTest@WebMvcTest

答案 1 :(得分:0)

就我而言,在使用Junit5运行时,我必须执行以下操作

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

这里abc.class是要测试的类

答案 2 :(得分:0)

能够使用下面的注释修复相同的问题。所以在这种情况下,Spring 只使用目标类 (Abc.class),而不是整个应用程序上下文。

@SpringBootTest(properties = "spring.main.lazy-initialization=true",
classes = {Abc.class})