Convert Spring XML declaration to Java code

Asked

Viewed 366 times

3

Can someone help me convert the Spring XML code that is just below into 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>

Here comes 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;
    }
}
  • 2

    edit your question with more information

  • I want to configure the "Bean" in the java application configuration.

  • Can’t a living soul show up to help me.

  • In my application I already have Webappconfig, what I want is to codidify in my Webappconfig bean that I posted.

  • @Geraldotorres managed to make the conversion?

2 answers

1

Hail!

Apparently you want to configure the Spring context via class using the annotation @Configuration, 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 secret is to extend the class org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter. It is she who will support your Spring MVC configuration.

Another point is that you will need to initialize the context. Thanks to Servlet 3 you no longer need to configure anything from web.xml. Just create a ServletInitializer in his classpath. Thus:

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[] { "/" };
    }
}

This way your context will be initialized together with the Web App.

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

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

0

Starting from the statement of his bean in XML, let’s first declare the resolve template, 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 that you have need to set up will look more or less 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, beyond the resolve template and also of tempalte engine you may need the view resolve, he’ll be something like this:

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

If you’re just gonna use thymeleaf you don’t need the other view resolve configured, then you can remove the bean raised in setupViewResolver.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.