4

In my last question I got answer to create ContextLoaderListener. I'm searching how can I add ContextLoaderListener without applicationContext.xml. I found Quick Start - Hello Spring Security enter link description here. After add I get error information

Caused by: java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!

But I dont config ContextLoaderListener in web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-      app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5" metadata-complete="true">

<display-name>PrimeFaces Web Application</display-name>
<context-param>
    <param-name>primefaces.THEME</param-name>
    <param-value>bootstrap</param-value>
</context-param>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>
<!-- context-param> <param-name>org.jboss.jbossfaces.WAR_BUNDLES_JSF_IMPL</param-name> 
    <param-value>true</param-value> </context-param -->
<!-- Welcome page -->
<welcome-file-list>
    <welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>

<!-- JSF mapping -->
<servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<!-- Map these files with JSF -->
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>

</web-app>

My RootConfiguration

package com.pl.war.ldap.config;
@Configuration
@EnableAutoConfiguration
@ComponentScan("com.pl.war.ldap.*")
public class Application extends SpringBootServletInitializer {

private static final Logger LOG = LoggerFactory.getLogger(AppConfig.class);


@Bean
public DataSource dataSource() {
    DataSource dataSource = null;
    JndiTemplate jndi = new JndiTemplate();
    try {
        dataSource = (DataSource) jndi
                .lookup("java:jboss/datasources/test");
    } catch (NamingException e) {
        LOG.error("NamingException for java:jboss/datasources/test", e);
    }
    return dataSource;
}


@Bean
LocalContainerEntityManagerFactoryBean entityManagerFactory(
        DataSource dataSource) {

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabase(Database.POSTGRESQL);
    adapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setPackagesToScan("com.pl.war.model");
    factoryBean.setPersistenceXmlLocation("META-INF/persistence.xml");
    factoryBean.setJpaVendorAdapter(adapter);
    factoryBean.setDataSource(dataSource);

    return factoryBean;
}


protected Properties buildHibernateProperties() {
    Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty("hibernate.dialect",
            "org.hibernate.dialect.PostgreSQL9Dialect");
    hibernateProperties.setProperty("hibernate.show_sql", "false");
    hibernateProperties.setProperty("hibernate.use_sql_comments", "false");
    hibernateProperties.setProperty("hibernate.format_sql", "false");
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "false");

    hibernateProperties.setProperty("hibernate.generate_statistics",
            "false");

    hibernateProperties.setProperty("javax.persistence.validation.mode",
            "none");

    // Audit History flags
    hibernateProperties.setProperty(
            "org.hibernate.envers.store_data_at_delete", "true");
    hibernateProperties.setProperty(
            "org.hibernate.envers.global_with_modified_flag", "true");

    return hibernateProperties;
}

@Bean
public PlatformTransactionManager transactionManager() {
    return new JpaTransactionManager();
}

@Bean
public TransactionTemplate transactionTemplate() {
    return new TransactionTemplate(transactionManager());
}

@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
    return new HibernateExceptionTranslator();
}
@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setSuffix(".xhtml");
    return viewResolver;
}

@Override
protected SpringApplicationBuilder configure(
        SpringApplicationBuilder application) {
    return application.sources(Application.class);
}
}

My getServletConfigClasses

 @Configuration
 @EnableWebSecurity
 @EnableGlobalAuthentication
 public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    // http.addFilter(casAuthenticationFilter());
    http.csrf().disable().authorizeRequests()
            .antMatchers("/home", "/css/**", "/**/*.css*", "/").permitAll()
            .anyRequest().authenticated().and().formLogin()
            .loginPage("/login").permitAll().and().logout()
            .logoutUrl("/logout").invalidateHttpSession(true)
            .logoutSuccessUrl("/");
    // http.exceptionHandling().authenticationEntryPoint(
    // casAuthenticationEntryPoint());
}

@Override
protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("password")
            .roles("USER");
}

@Bean
public AuthenticationManager authenticationManager() throws Exception {
    return super.authenticationManagerBean();

}

}

and SpringMvcInitializer

    @Order(1)
    public class SpringMvcInitializer extends
    AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { Application.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[] { WebSecurityConfig.class };
}

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

}
}


public class MessageSecurityWebApplicationInitializer extends
    AbstractSecurityWebApplicationInitializer {

}

I found a few similar issues

https://stackoverflow.com/questions/22729725/why-this-spring-application-with-java-based-configuration-dont-work-properly

or example

http://www.mkyong.com/spring-security/spring-security-hello-world-annotation-example/

But I can't resolve my problem

Thanks for help

Community
  • 1
  • 1
luprogrammer
  • 155
  • 1
  • 3
  • 12
  • You are using Spring boot, then use spring boot, your configuration is trying very hard to not use spring boot. Adding a `ContextLoaderListener` will not work because spring boot is taking care of that. Also what is it you want, generally your web.xml is useless in a Spring Boot application (especially when you use the main method to run) else you should use the `SpringBootServletInitialiszer` to bootstrap your application not a web.xml. – M. Deinum Jan 04 '15 at 13:48
  • As already mentioned in that question you are trying to inject using Spring into a JSF or CDI managed bean and that is not going to work. The `@Autowired` is useless, regardless how much configuration you throw at it. – M. Deinum Jan 04 '15 at 13:50
  • My main purpose is create project Spring security(spring-boot-autoconfig without applicationContext)+ jsf2.0+ primefaces+ JPA. Currently web.xml has primefaces configuration. I'm not using only bootstrap. I'm using primefaces with bootstrap theme. I try change `@ManagedBean @RequestScoped public class LoginBean implements Serializable {` and `@Inject private AuthenticationManager authenticationManager;` but I have null in authenticationManager. I'm always using EJB. I have never used Spring before. – luprogrammer Jan 04 '15 at 14:32
  • I found many good tutorials with jsp or thymeleaf but only one with [Spring security+ jsf2.0+ primefaces+ JPA] (http://marco-ng.blogspot.com/2014/02/primefaces-jsf2-spring-security-spring.html) But they are using applicationContext that's why I have a big problem. Summarizing when I'm using spring-boot I need `@Order(1) public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {` or should I remove it ? – luprogrammer Jan 04 '15 at 14:44
  • As stated you are using Spring boot and that changes things. Instead of blindly following tutorials I would suggest trying to understand what spring boot does for you and work with the framework. As also stated before you are mixing different strategies `@Inject` works in CDI not in JSF managed beans (you have to use `@ManagedBean`), basically the same as with `@Autowired` that only works for Spring Managed beans not JSF or CDI. Invest sometime in understanding the technologies you are using it will save you time and frustration. – M. Deinum Jan 04 '15 at 18:05

0 Answers0