Ravi Jain Ravi Jain - 10 months ago 50
Java Question

ViewResolver using Java annotation

Is it possible in Spring 3.1.1 to configure a view resolver using Java annotations?

I am done with all configurations using Java annotations, but I am stuck at view resolver.


package com;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.JstlView;

public class AppConfig
//Other bean declarations

public UrlBasedViewResolver urlBasedViewResolver()
UrlBasedViewResolver res = new InternalResourceViewResolver();

return res;

I used this code and ran the application, but it's not returning the appropriate view. However, if I configure a viewresolver in the
file, it works fine.

Answer Source

Your class should extend WebMvcConfigurerAdapter class. please have a look at below example

public class MvcConfiguration extends WebMvcConfigurerAdapter{

    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        return resolver;