복붙노트

[SPRING] ApplicationContext를로드하지 못했습니다 (주석 첨부).

SPRING

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

예외 (많은 예외, 주 :  ApplicationContext를로드하지 못했습니다. 이름이 'defaultServletHandlerMapping'인 bean을 생성하는 중 오류가 발생했습니다. [org.springframework.web.servlet.HandlerMapping] 인스턴스 생성에 실패했습니다 : 팩토리 메소드 'defaultServletHandlerMapping'이 예외를 던졌습니다. ServletContext는 기본 서블릿 처리를 구성하는 데 필요합니다. )

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

다른 설정 파일들 이 프로젝트에서 자식 프로젝트 무슨 일이야? 왜 오류입니까?

해결법

  1. ==============================

    1.테스트에는 ServletContext가 필요합니다 : add @WebIntegrationTest

    테스트에는 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

    최신 정보 Spring Boot 1.4.x 이상에서는 @WebIntegrationTest가 더 이상 사용되지 않습니다. @SpringBootTest 또는 @WebMvcTest

  2. from https://stackoverflow.com/questions/36519220/failed-to-load-applicationcontext-with-annotation by cc-by-sa and MIT license