Convert Spring XML declaration to Java code

3

Can anyone help me convert the Spring XML code that is just below a Java code?

<bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
    <property name="dialects">
        <set>
            <bean class="org.thymeleaf.spring3.dialect.SpringStandardDialect" />
            <ref bean="pagesDialect" />
        </set>
    </property>
</bean>

There goes my WebAppConfig :

package com.ghtecnologia.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.ghtecnologia"})
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    // Maps resources path to webapp/resources
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    // Provides internationalization of messages
    @Bean
    public ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("messages");
        return source;
    }

    @Bean
    public SessionLocaleResolver sessionLocaleResolver() {
        SessionLocaleResolver localeResolver = new SessionLocaleResolver();
        return localeResolver;
    }

    @Bean
    public LocaleChangeInterceptor LocaleChangeInterceptor() {
        LocaleChangeInterceptor localechangeInterceptor = new LocaleChangeInterceptor();
        return localechangeInterceptor;
    }
}
    
asked by anonymous 15.07.2015 / 16:01

2 answers

1

Save!

Apparently you want to set the Spring context via class using the @Configuration annotation, right?

If so, use this setting as a reference:

@Configuration
@EnableWebMvc
@Import({MinhaConfigDeServicos.class})
@PropertySource(value = "classpath:META-INF/minhaspropriedades.properties")
public class WebAppConfig extends WebMvcConfigurerAdapter {
    // vc pode utilizar essa referencia para capturar as propriedades
    @Inject
    protected Environment environment;

    // aqui eh o seu template resolver.
    // eu uso o thymeleaf. mas eh aqui que vc configura de acordo com o seu XML da pergunta
    @Bean
    public ServletContextTemplateResolver templateResolver() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode("HTML5");
        templateResolver.setCacheable(false);

        return templateResolver;
    }
}

The key is to extend the org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter class. This is the one that will support your Spring MVC configuration.

Another point is that you will need to initialize the context. Thanks to Servlet 3 you no longer have to configure anything of web.xml . Just create a ServletInitializer in your classpath . This way:

public class SpringMvcWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        // a sua configuracao web
        return new Class[] { WebAppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
       return null;
    }

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

That way your context will be initialized along with the Web App.

If you still have questions, put in the comments I try to help you.

EDIT: If you can, give more information about your environment (application server, Spring version used, etc.) to better formulate the answer.

    
21.07.2015 / 15:34
0

From the declaration of your bean in XML, let's first declare the template resolve , it will look like this:

@Bean
public ServletContextTemplateResolver templateResolver() {
    final ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
    resolver.setPrefix("/WEB-INF/templates/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode("HTML5");
    return resolver;
}
The template engine , bean you need to configure will look something like this:

@Bean
public SpringTemplateEngine templateEngine() {
    final SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(this.templateResolver());

    final Set<IDialect> dialects = new HashSet<>();
    dialects.add(new SpringStandardDialect());

    // inclua o outro dialeto, como não sei o tipo não coloquei, já que pode ser um customizado
    // dialects.add(pagesDialect);

    engine.setDialects(dialects);
    return engine;
}

Finally, in addition to the template and temparte engine you may need the view resolve , it will look something like this: / p>

@Bean
public ThymeleafViewResolver thymeleafViewResolver() {
    final ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(this.templateEngine());
    return resolver;
}

If you only use thymeleaf you do not need the other view resolve configured, then you can remove bean created in setupViewResolver .

    
28.07.2015 / 19:13