2016-09-20 6 views
7

私は同様の質問について他の回答を読んでいますが、私の問題の解決策は見つかりませんでした。私はTomcat7サーバーとHibernateを使用して私のPostgreSQLリモートDBに接続するSpringアプリケーションを持っています。 私のフレームワークのバージョンは次のとおりです。 Springフレームワーク4.2.2 春のセキュリティ3.2.5 にHibernate 4.3.6Hibernateはリモートサーバ上の現在のスレッドのトランザクション同期セッションを取得できませんでした

私はlocalhostのすべての私のアプリは結構です実行されますが、私は私のサーバーにデプロイするとき、私はこのエラーを受け取りますログイン時に:

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     Class[] config = {AppConfig.class}; 
     return config; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     Class[] config = {SecurityConfig.class, HibernateConfig.class}; 
     return config; 
    } 

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

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread 
    org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) 
    org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) 
    org.myapp.spring.dao.generic.GenericDAOImpl.getSession(GenericDAOImpl.java:59) 
    org.myapp.spring.dao.impl.DeveloperDaoImpl.findByUsername(DeveloperDaoImpl.java:51) 
    org.myapp.spring.service.impl.DeveloperServiceImpl.findByUsername(DeveloperServiceImpl.java:149) 
    org.myapp.spring.web.security.UserDetailsServiceImpl.loadUserByUsername(UserDetailsServiceImpl.java:23) 
    org.myapp.spring.web.security.MyAuthenticationProvider.authenticate(MyAuthenticationProvider.java:30) 
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167) 
    org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192) 
    org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93) 
    org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) 
    org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) 
    org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) 
    org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) 
    org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) 
    org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) 
    org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262) 

私は2つのinizializerファイルを持っています

@Component 
public class SecurityWebApplicationInizializer extends AbstractSecurityWebApplicationInitializer { 
} 

と3つのコンフィグファイル:最後に

@EnableWebMvc 
@ComponentScan({ "org.myapp.spring.*" }) 
@EnableTransactionManagement 
@PropertySource(value="classpath:myapp.properties") 
public class AppConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { 

    @Autowired 
    private TokenInterceptor tokenInterceptor; 
    private ApplicationContext applicationContext; 
    private static final String UTF8 = "UTF-8"; 

    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) { 
     this.applicationContext = applicationContext; 
    } 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
     registry.addInterceptor(tokenInterceptor); 
    } 

//other methods 
} 

@Configuration 
@EnableWebSecurity 
@EnableTransactionManagement 
@ComponentScan("org.myapp.spring.web.security") 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired private MyAuthenticationProvider authProvider; 
@Autowired private UserDetailsService userDetailsService; 

@Autowired 
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
    auth.authenticationProvider(authProvider); 
    auth.userDetailsService(userDetailsService); 
} 

@Override 
public void configure(WebSecurity web) throws Exception { 
    DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); 
    handler.setPermissionEvaluator(permissionEvaluator()); 
    web.expressionHandler(handler); 
} 

@Bean 
public PermissionEvaluator permissionEvaluator() { 
    return new MyPermissionEvaluator(); 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().and() 
    .formLogin().loginPage("/html/login").defaultSuccessUrl("/html/index", true).permitAll() 
    .and() 
    .logout().logoutUrl("/html/logout").logoutSuccessUrl("/html/login?logout").invalidateHttpSession(true).clearAuthentication(true).permitAll() 
    .and() 
    .authorizeRequests() 
    .antMatchers("/html/forbidden").permitAll() 
    .antMatchers("/html/logistic").permitAll() 
    .antMatchers("/html/ajax/logistic").permitAll() 
    .antMatchers("/html/res/**").permitAll() 
    .antMatchers("/html").authenticated() 
    .antMatchers("/html/**").authenticated() 
    .and() 
    .exceptionHandling().accessDeniedPage("/html/forbidden"); 
} 

}

と、:

@Configuration 
@EnableTransactionManagement 
@ComponentScan({ "org.myapp.spring.configuration" }) 
@PropertySource(value = { "classpath:hibernate.properties" }) 
public class HibernateConfig { 

@Autowired 
private Environment environment; 

@Bean 
public LocalSessionFactoryBean sessionFactory() { 
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
    sessionFactory.setDataSource(dataSource()); 
    sessionFactory.setPackagesToScan(new String[] { "org.myapp.spring.model"}); 
    sessionFactory.setHibernateProperties(hibernateProperties()); 

    try { 
     sessionFactory.afterPropertiesSet(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return sessionFactory; 
} 

@Bean 
public DataSource dataSource() { 
    DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
    dataSource.setDriverClassName(environment.getRequiredProperty("hibernate.connection.driver_class")); 
    dataSource.setUrl(environment.getRequiredProperty("hibernate.connection.url")); 
    dataSource.setUsername(environment.getRequiredProperty("hibernate.connection.username")); 
    dataSource.setPassword(environment.getRequiredProperty("hibernate.connection.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")); 
    return properties; 
} 

@Bean 
@Autowired 
public HibernateTransactionManager transactionManager(SessionFactory s) { 
    HibernateTransactionManager txManager = new HibernateTransactionManager(); 
    txManager.setSessionFactory(s); 
    return txManager; 
} 
} 

GenericDaoImplは次のとおりです。

@Repository 
public abstract class GenericDAOImpl<T> implements DAO<T> { 

    @Autowired 
    private SessionFactory sessionFactory; 

protected Session getSession() { 
      return sessionFactory.getCurrentSession(); 
     } 

} すべてのDAOはこのクラスを拡張し、独自の@Repositoryアノテーションを持っています。

すべてのサービスには@トランザクションという注釈が付けられています。私は本当にこれが何ができるか分からない

@Service 
@Transactional 
public class UserDetailsServiceImpl implements UserDetailsService, MyUserDetailsService { 

    @Autowired private DeveloperService devService; 
    @Autowired private AuthorizationService authorizationService; 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
     if(username == null) { 
      throw new UsernameNotFoundException("User not found"); 
     } 
     Developer dev = devService.findByUsername(username); 

     if(dev == null) { 
      throw new UsernameNotFoundException("User not found"); 
     } 
     MyUserDetails user = new MyUserDetails(); 
     user.setUsername(dev.getUsername()); 
     user.setPassword(dev.getPassword()); 
     user.setMaxAuthorityByIndex(dev.getRole()); 
     return user; 
    } 

:これはUserDetailsS​​erviceの実装です。サーバー上の設定が間違っている可能性がありますか?私にとって問題があなたのサービスの2つのインスタンスを持っているということです...取引で1が使用されていません。

+0

にこれを追加...正しいように見えますあなたは、それをしない異なる構成のあまりにも多くのもののコンポーネントスキャンです。セキュリティと休止状態の設定もルート設定の一部にする必要があります。サーブレットの設定は、Web関連のもの(コントローラー、ビュー、およびそのインフラストラクチャー)で構成されている必要があります。 –

+0

私はただ1つの設定ファイルを使うべきだと言っていますか? – zuno

+0

いいえ...私は、あなたが何をどこで、どこであなたがコンポーネントスキャニングを使用しているか、適切なタイプのクラスが適切なコンポーネントによってロードされるべきであることに注意するべきだと言います。 'ContextLoaderListener'は、理想的には、' DataSource'、 'EntityManagerFactory'のようなインフラストラクチャサービスだけでなく、サービス、リポジトリなども含むべきです。' DispatcherServlet'は、Web関連のもの '@ EnableWebMvc'と、コントローラ、 。 –

答えて

0

があなたの

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("current_session_context_class","org.springframework.orm.hibernate4.SpringSessionContext"); 
     return properties; 
    } 
関連する問題