4

I understand that it is possible to configure a Spring application without the use of XML config files, and have commited to this method. I am not sure, however, how to declare HTTP interceptors in this manner. I am using this tutorial, which declares the following XML.

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/welcome.htm">welcomeController</prop>
            </props>
        </property>
        <property name="interceptors">
            <list>
                <ref bean="maintenanceInterceptor" />
                <ref bean="executeTimeInterceptor" />
            </list>
        </property>
    </bean>

    <bean
    class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="executeTimeInterceptor" />
            </list>
        </property>
    </bean>

    <bean id="welcomeController"
                  class="com.mkyong.common.controller.WelcomeController" />
    <bean class="com.mkyong.common.controller.MaintenanceController" />

    <bean id="executeTimeInterceptor"
                 class="com.mkyong.common.interceptor.ExecuteTimeInterceptor" />

    <bean id="maintenanceInterceptor"
                class="com.mkyong.common.interceptor.MaintenanceInterceptor">
        <property name="maintenanceStartTime" value="23" />
        <property name="maintenanceEndTime" value="24" />
        <property name="maintenanceMapping" value="/SpringMVC/maintenance.htm" />
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

How to do this in Java? There is no @Interceptor annotation.

SpringApplication.java

@SuppressWarnings("WeakerAccess")
@SpringBootApplication
@PropertySources(value = {@PropertySource("classpath:/application.properties")})

public class SpringbackendApplication {

    @Autowired
    Environment env;

    public static void main(String[] args) {
        SpringApplication.run(SpringbackendApplication.class, args);
        initializeFirebase();
    }

    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Bean
    public UserController userController() {
        UserController userController = new UserController(getUserDAO(), getYodleeDAO());
        userController.setCobrandSession(cobrandSession());
        userController.setUserSessionManager(userSessionManager());
        userController.setAccountsService(accountsService());
        userController.setTransactionsService(transactionsService());
        return userController;
    }

    @Bean
    public TestController testController() {
        TestController testController = new TestController();
        testController.setCobrandSession(cobrandSession());
        testController.setUserSessionManager(userSessionManager());
        testController.setAccountsService(accountsService());
        testController.setTransactionsService(transactionsService());
        return testController;
    }

    @Bean
    public CobrandSession cobrandSession() {
        CobrandSession cobrandSession = new CobrandSession();
        cobrandSession.setApiBase(this.env.getProperty("API_BASE"));
        cobrandSession.setLogin(this.env.getProperty("LOGIN"));
        cobrandSession.setPassword(this.env.getProperty("PASSWORD"));
        cobrandSession.setLocale(this.env.getProperty("LOCALE"));
        cobrandSession.setRestTemplate(restTemplate());
        cobrandSession.setGson(gson());
        return cobrandSession;
    }

    @Bean
    public AccountsService accountsService() {
        AccountsService accountsService = new AccountsService();
        accountsService.setApiBase(this.env.getProperty("API_BASE"));
        accountsService.setRestTemplate(restTemplate());
        accountsService.setGson(gson());
        return accountsService;
    }

    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setOutputStreaming(false); // If we don't turn this off, we may get HttpRetryException on 401's.
        return new RestTemplate(factory);
    }

    @Bean
    public Gson gson() {
        return new Gson();
    }

}
Community
  • 1
  • 1
David Ferris
  • 2,215
  • 6
  • 28
  • 53
  • You can add `@EnableAutoConfiguration` on your Application class and then create another class which extends `WebMvcConfigurerAdapter`. Then override it's `addInterceptors()` method – staszek Nov 07 '16 at 19:58
  • Will extending `WebMvcConfigurerAdapter` ensure that `addInterceptors()` is run, or would I have to call it from anywhere? – David Ferris Nov 07 '16 at 20:00
  • It should :) When you mark your main class (that with `@SpringBootApplication` ) with annotation like `@EnableAutoConfiguration` or similar (from configuration "family") you tell spring to search for configuration classes - they are annotated with e.g. `@Configuration` annotations. You can use `@ComponentScan` to tell which packaged should be scanned against configuration classes. Please refer http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-using-springbootapplication-annotation.html – staszek Nov 07 '16 at 20:04

2 Answers2

4

To move your Spring beans defined in an XML file to a Configuration class (marked with @Configuration) you would need something like this:

@Configuration
public class MyConfig {
    @Bean(name="executeTimeInterceptor")
    public ExecuteTimeInterceptor getExecuteTimeInterceptor() {
        return new com.mkyong.common.interceptor.ExecuteTimeInterceptor();
    }

    @Bean(name="maintenanceInterceptor")
    public MaintenanceInterceptor getMaintenanceInterceptor(@Value("${properties.maintenanceStartTime}") int maintenanceStartTime,
                                                            @Value("${properties.maintenanceEndTime}") int maintenanceEndTime,
                                                            @Value("${properties.maintenanceMapping}") String maintenanceMapping) {

        MaintenanceInterceptor myInt = new MaintenanceInterceptor();
        myInt.setMaintenanceStartTime(maintenanceStartTime);
        myInt.setmMaintenanceEndTime(maintenanceEndTime);
        myInt.setMaintenanceMapping(maintenanceMapping);
        return myInt;
    }
}

...then in some propertiesFile.properties on the classpath add these...

properties.maintenanceStartTime=23
properties.maintenanceEndTime=24
properties.maintenanceMapping=/SpringMVC/maintenance.htm

EDIT

I see you are getting your props from the Environment, so instead of @Value injection, use the way you have it in your code right now.

Mechkov
  • 4,294
  • 1
  • 17
  • 25
3

You have to override WebMvcConfigurerAdapter.addInterceptors() method and add your interceptors:

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

Don't forget to mark your class with @Configuration

staszek
  • 251
  • 2
  • 9