web-dev-qa-db-ja.com

ApplicationContextの読み込みに失敗しました(注釈付き)

これはテスト用の私のクラスです。

@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:org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.Java:124)のApplicationContextをorg.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.Java:でロードできませんでした: 83)org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.Java:83)atframe.testframetest.org.springframework.test.atframe.test.testframe.org.springframework.test.context.support。 .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.m org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.Java:291)のorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunnerのodel.ReflectiveCallable.run(ReflectiveCallable.Java:12) Java:249)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。 org.springframework.test.context.junit4.statements.RunAfterTestClaのevaluate(RunBeforeTestClassCallbacks.Java:61) orgでorg.junit.runners.ParentRunner.run(ParentRunner.Java:363)でssCallbacks.evaluate(RunAfterTestClassCallbacks.Java:70)org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.Java:193)で.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)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) )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)原因:org.springframework.beans.factory.BeanCreationException:「defa」という名前のBeanの作成エラークラスorg.springframework.web.servlet.config.annotation.DelegatingWebMvcConfigurationで定義されているultServletHandlerMapping ':ファクトリメソッドによるBeanのインスタンス化に失敗しました。ネストされた例外はorg.springframework.beans.BeanInstantiationException:インスタンス化に失敗しました[org.springframework.web.servlet.HandlerMapping]:ファクトリメソッド 'defaultServletHandlerMapping'は例外をスローしました。ネストされた例外はJava.lang.IllegalArgumentExceptionです:org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.Java:599)でorg.springframework.beans.factory.supportでデフォルトのサーブレット処理を設定するには、ServletContextが必要です。 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.Java:1018)のAbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.Java:1123) 510)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.DefaultSingletonBeanRegis try.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-基本構成ファイル。

@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
何がいけないのか教えてください?なぜエラーですか?

11
makson

テストにはServletContextが必要です。add@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

[〜#〜] update [〜#〜]Spring Boot 1.4.x以降では@WebIntegrationTestは推奨されなくなりました。 @SpringBootTestまたは@WebMvcTest

20
ndrone