SecurityConfig Java file error - java

I am new to Spring and trying to create authentication for RESTful API using Spring. I am getting the following error, how can I resolve this?
StackTrace:
Error creating bean with name 'webConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
WebConfig.java
#Configuration
#EnableWebMvc
#ComponentScan("com.base")
public class WebConfig extends WebSecurityConfigurerAdapter{
#Autowired
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
#Autowired
private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().
withUser("temporary").password("temporary").roles("ADMIN").and().
withUser("user").password("userPass").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/api/foos").authenticated()
.and()
.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout();
}
}
MySavedRequestAwareAuthenticationSuccessHandler.java
#Component
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl()
|| (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) {
requestCache.removeRequest(request, response);
clearAuthenticationAttributes(request);
return;
}
clearAuthenticationAttributes(request);
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}

Use #EnableWebSecurity for web security configuration
Split the WebConfig from the WebSecurityConfig to different classes.

Related

Spring Security config - 403 forbidden

I Use spring 5.0.7.RELEASE and I need to add basic authentication for my spring application and this is a pretty old application. That is why it uses the old way of registering the config classes. I have added the SecurityConfig class and imported it in the SpringMvcConfig as shown below
#Configuration
#EnableWebMvc
#ComponentScan( basePackages = {
"com.test" },
excludeFilters = {
#ComponentScan.Filter( Configuration.class )
} )
#ImportResource("classpath:/spring-context.xml")
#EnableSwagger2
#Import({SwaggerConfig.class, SecurityConfig.class})
public class SpringMvcConfig extends WebMvcConfigurationSupport {
#Autowired private ApplicationContext applicationContext;
private static final String[] RESOURCE_BUNDLES = new String[] { "MessageResources" };
private static final String[] YAML_RESOURCE_BUNDLES = new String[] { "messages" };
/**
* Configures the Jackson object mapper
*/
#Bean( name = "objectMapper" )
public ObjectMapper getObjectMapper( JacksonService jacksonService ) {
return jacksonService.getObjectMapper();
}
/**
* Configures the ApplicationContextProvider
*/
#Bean( name = "applicationContextProvider" )
public ApplicationContextProvider getApplicationContextProvider() {
return new ApplicationContextProvider();
}
}
and here is the web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.test.SpringMvcConfig</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security Configuration -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and here is my SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("test")
.password("testpwd")
.roles("USER");
}
}
I get a 403 forbidden The server understood the request but refuses to authorize it. I also added
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
}

Spring security oauth/token returns 401

I am trying to create a simple app with Spring and Spring Security.
When I hit the default localhost:8080/oauth/token endpoint with username and password in the body I expect to get a token or an error if a given user does not exist.
I get 401 though. Why is that?
Here are some of my config files:
#EnableResourceServer
#Configuration
public static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(PUBLIC_URIS).permitAll();
}
}
#EnableAuthorizationServer
#Configuration
public static class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManagerBean;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(CLIENT_ID)
.authorizedGrantTypes(GRANT_TYPE)
.scopes(SCOPE);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManagerBean);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.allowFormAuthenticationForClients();
}
Security class:
#Configuration
#EnableWebSecurity
public class Security extends WebSecurityConfigurerAdapter {
#Autowired
private UserService usersService;
private PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(usersService).passwordEncoder(passwordEncoder);
}
}
And web.xml:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>CORS</filter-name>
<filter-class>pl.kabat.security.configuration.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
From the HTTP specs:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401
"The HTTP 401 Unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource."
In other words, what you're getting is exactly an authentication error.

Two different authenticationManagers for two different dispatcherServlet

In my web.xml I have two different dispatcher servlets, one of them has all beans from root context, second dispatcher servlet has another authenticationManager.
as sayed:
In the Web MVC framework, each DispatcherServlet
has its own WebApplicationContext, which inherits all the beans already defined in the root
WebApplicationContext. The root WebApplicationContext should contain all the infrastructure
beans that should be shared between your other contexts and Servlet instances. These inherited beans
can be overridden in the servlet-specific scope, and you can define new scope-specific beans local to
a given Servlet instance.
So my new authenticationManager must override the same bean from root context. This authenticationManager has another daoAuthenticationProvider, which has another userDetailsService. But when I want to log in in system from path for second dispathcer servlet, spring uses authenticationManager from root context.
It is web.xml:
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>ua.translate.AppConfig</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>ua.translate.AppConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>adminDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>ua.admin.AdminConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>adminDispatcher</servlet-name>
<url-pattern>/bulbular/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
It is AdminConfig.class:
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = {"ua.admin"})
#EnableTransactionManagement
#EnableAspectJAutoProxy(proxyTargetClass = true)
public class AdminConfig extends WebMvcConfigurerAdapter{
}
It is WebSecurityConfigurerAdapter implementation, which is located in ua.admin package and have new authenticationManager:
#EnableWebSecurity
#Configuration
#ComponentScan(basePackages = {"ua.translate.handler","ua.translate.service.impl"})
#Order(1)
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
protected CustomSuccessHandler customSuccessHandler;
#Autowired
#Qualifier("customAccessDeniedHandler")
protected AccessDeniedHandler accessDeniedHandler;
#Autowired
#Qualifier("adminDetailsService")
private UserDetailsService uds;
#Override
public void configure(WebSecurity web){
web
.ignoring()
.antMatchers(new String[]{"/resources/**"});
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/bulbular/**")
.authorizeRequests()
.antMatchers("/bulbular/login").permitAll()
.anyRequest().hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/bulbular/login")
.permitAll()
.successHandler(customSuccessHandler)
.failureUrl("/bulbular/login?error")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/j_spring_security_check")
.and()
.logout().deleteCookies("JSESSIONID")
.logoutUrl("/bulbular/logout")
.logoutSuccessUrl("/bulbular/login?logout")
.and()
.csrf()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
}
#Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
impl.setUserDetailsService(uds);
impl.setPasswordEncoder(bcryptEncoder());
impl.setHideUserNotFoundExceptions(false);
return impl;
}
#Bean
public PasswordEncoder bcryptEncoder(){
return new BCryptPasswordEncoder();
}
#Bean(name = "authenticationManager")
public ProviderManager getProviderManager(){
List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(daoAuthenticationProvider());
ProviderManager providerManager = new ProviderManager(providers);
return providerManager;
}
This class is WebSecurityConfigurer implementation in root context, it is base class for two another classes:
#EnableWebSecurity
#ComponentScan(basePackages = {"ua.translate"})
#Order(99)
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
protected CustomSuccessHandler customSuccessHandler;
#Autowired
#Qualifier("customAccessDeniedHandler")
protected AccessDeniedHandler accessDeniedHandler;
#Autowired
protected PersistentTokenRepository tokenRepository;
#Autowired
#Qualifier("userDetailsServiceImpl")
protected UserDetailsService uds;
#Override
public void configure(WebSecurity web){
web
.ignoring()
.antMatchers(new String[]{"/resources/**"});
}
#Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider impl = new DaoAuthenticationProvider();
impl.setUserDetailsService(uds);
impl.setPasswordEncoder(bcryptEncoder());
impl.setHideUserNotFoundExceptions(false);
return impl;
}
#Bean(name = "authenticationManager")
public ProviderManager getProviderManager(){
List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(daoAuthenticationProvider());
ProviderManager providerManager = new ProviderManager(providers);
return providerManager;
}
#Bean
public PasswordEncoder bcryptEncoder(){
return new BCryptPasswordEncoder();
}
There are two subclasses, which is located in root context:
#Configuration
#EnableWebSecurity
public class SecurityConfig {
#Configuration
#Order(3)
public static class AppSecurityConfigClient extends AppSecurityConfig{
#Override
public void configure(WebSecurity web){
web
.ignoring()
.antMatchers(new String[]{"/resources/**"});
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/client/registration*").anonymous()
.antMatchers("/index","/translators","/orders","/client/login*","/client/confirmation").permitAll()
.antMatchers("/client/**").hasRole("CLIENT")
.and()
.formLogin()
.loginPage("/client/login")
.permitAll()
.successHandler(customSuccessHandler)
.failureUrl("/client/login?error")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/j_spring_security_check")
.and()
.logout().deleteCookies("JSESSIONID")
.logoutUrl("/client/logout")
.logoutSuccessUrl("/client/login?logout")
.and()
/*!!!!Доделать saved request url!!!!*/
.rememberMe().tokenRepository(tokenRepository)
.tokenValiditySeconds(86400)
.and()
.csrf()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler);
}
}
#Configuration
#Order(2)
public static class AppSecurityConfigTranslator extends AppSecurityConfig {
#Override
public void configure(WebSecurity web){
web
.ignoring()
.antMatchers(new String[]{"/resources/**"});
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/translator/**")
.authorizeRequests()
.antMatchers("/translator/registration*").anonymous()
.antMatchers("/translator/index","/translator/login*","/translator/confirmation").permitAll()
.antMatchers("/translator/**").hasRole("TRANSLATOR")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/translator/login")
.permitAll()
.successHandler(customSuccessHandler)
.failureUrl("/translator/login?error")
.usernameParameter("username")
.passwordParameter("password")
.loginProcessingUrl("/j_spring_security_check")
.and()
.logout().deleteCookies("JSESSIONID")
.logoutUrl("/translator/logout")
.logoutSuccessUrl("/translator/login?logout")
.and()
/**
* Доделать saved request url!!!
*/
.rememberMe().tokenRepository(tokenRepository)
.tokenValiditySeconds(86400)
.and()
.csrf()
.and()
.exceptionHandling()
.accessDeniedHandler(accessDeniedHandler)
.and()
.userDetailsService(uds);
}
}
}
So, adminDispatcher servlet uses ua.admin.AdminConfig, which in turn scan ua.admin package, and find WebSecurityConfigurerAdapter implementation with second authenticationManager implementation.
/bulbular/ - it is path for this dispathcer servlet, and path for http configuration in WebSecurityConfigurerAdapter implementation. But when I want to log in from /bulbular/login page, spring uses implementatation from SecurityConfig.class - class from root context. Help please!!!!

Can't login with Java Configuration and Spring Security 3.2

I'm having trouble after switch my application to Spring security 3.2 and Java Configuration. Originally it was configured with xml but once I've made all the changes to use annotations every time I try to access to localhost:8080/mysite/login I have this error "No mapping found for HTTP request with URI [/mysite/login] in DispatcherServlet with name 'mvc-dispatcher". This is my configuration:
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.mypackages.*" })
#Import({ DatabaseConfig.class, SecurityConfiguration.class, SocialConfig.class })
#PropertySource(value = {"classpath:/mysite.properties"})
public class AppConfig extends WebMvcConfigurerAdapter {
//in this class I define the viewResolver, messageSource, localeResolver, some properties, etc, but I don't think they would be necessary for my problem
}
"configure" method at SecurityConfiguration.java
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login").defaultSuccessUrl("/welcome")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers("/welcome*").authenticated()
.and()
.rememberMe()
.and().headers().xssProtection().frameOptions().httpStrictTransportSecurity()
.and()
.apply(new SpringSocialConfigurer());
}
web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.myapp.config.AppConfig
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.myapp.config.AppConfig</param-value>
</context-param>
As far as I understand, with the login page setted in the "configure" method (SecurityConfiguration.java) should be enough to show the login page when I access to localhost:8080/mysite/login, I've been reading some examples I don't think the error is on the security configuration, am I missing something?.
Any help will be appreciated
UPDATE
I've been searching and it seems like my error was to include both web.xml and an extension of AbstractAnnotationConfigDispatcherServletInitializer so I decided to remove the web.xml, and modify SpringMvcInitializer:
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class, SecurityConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DatabaseConfig.class };
}
But still have the same error No mapping found for HTTP request with URI [/siteserver/login] in DispatcherServlet with name 'dispatcher', pleeeaaaase does anybody has a clue about what's going on?
If you are using a spring security, i think you should also configure application context.xml which should be in your WEB-INF folder.
Change the location of your context config. I believe it should be your applicationContext.xml and all the confifuration will go inside that.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
You can also try adding the listener class in your web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Spring MVC - DispatcherServlet by annotations

I got spring MVC application.
It runs on Tomcat 7.
By now i got this part in my web.xml file:
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/app-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Is there any way to init it by annotations? I got a MainSettings.java class where all my beans are initialyzed by #Bean annotation. So how do i initDispatherServlet there?
Here is the example with comments. Hope this helps you.
public class ApplicationInitializer implements WebApplicationInitializer {
//Called first when the application starts loading.
public void onStartup(ServletContext servletContext)
throws ServletException {
System.out.println("Inside application initializer...");
//Registering the class that incorporates the annotated DispatcherServlet configuration of spring
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(DispatcherConfig.class);
//Adding the listener for the rootContext
servletContext.addListener(new ContextLoaderListener(rootContext));
//Registering the dispatcher servlet mappings.
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
Writing this because Japs's answer leads to creation of another context, which doesn't see the contents of the security context.
public class WebInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
private static final Log LOGGER = LogFactory.getLog(WebInitializer.class);
#Override
protected Class<?>[] getRootConfigClasses() {
/* this is where you will return you config class
* your root config class should #Import other configs
* to make them work without needing them to add there
*/
return new Class[] { ViewConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

Categories