0
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
          ...
          <property name="additionalDialects">
            <set>
              <!-- Note the package would change to 'springsecurity3' if you are using that version -->
              <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
            </set>
          </property>
          ...
        </bean>

Não estou usando o Spring-boot.

Gostaria de saber como encaixar o treixo acima no formato java em umas das classes abaixo:

@Configuration
public class ThymeleafConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public ViewResolver thymeleafViewResolver(ITemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

        viewResolver.setOrder(1);
        viewResolver.setTemplateEngine(templateEngine);
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setViewNames(new String[]{"*.html"});

        return viewResolver;
    }

    @Bean
    public ITemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();

        templateEngine.setTemplateResolver(templateResolver);
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.addDialect(new Java8TimeDialect());//adicionado para trabalhar com data do java8
        templateEngine.addDialect(new SpringSecurityDialect());

        return templateEngine;
    }



    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();

        templateResolver.setApplicationContext(this.applicationContext);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(false);

        return templateResolver;
    }

}

e

public class SpringWebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {         

            AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();

        applicationContext.scan(SpringWebInitializer.class.getPackage().getName());


        servletContext.addListener(new ContextLoaderListener(applicationContext));
        servletContext.addListener(new RequestContextListener());

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", dispatcherServlet(applicationContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter());
        characterEncodingFilter.setAsyncSupported(true);
        characterEncodingFilter.addMappingForServletNames(dispatcherTypes(true), false, "dispatcher");

        FilterRegistration.Dynamic inViewSession = 
                servletContext.addFilter(
                        "Spring OpenEntityManagerInViewFilter", 
                        new OpenEntityManagerInViewFilter());
        inViewSession.setAsyncSupported(Boolean.TRUE);
        inViewSession.addMappingForUrlPatterns(null, true, "/*");

        FilterRegistration.Dynamic securityFilter = 
                                servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
                securityFilter.setAsyncSupported(Boolean.TRUE);
                securityFilter.addMappingForUrlPatterns(null, true, "/*");
    }

    private DispatcherServlet dispatcherServlet(WebApplicationContext applicationContext) {
          DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);

        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        return dispatcherServlet;
    }

    private CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();

        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        return characterEncodingFilter;
    }

    private EnumSet<DispatcherType> dispatcherTypes(boolean asyncSupported) {
        return (asyncSupported ?
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC) :
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE));
    }
}

e

@EnableWebMvc
@Configuration
@ComponentScan("com.aplicacao.thymeleaf")
public class WebConfig extends WebMvcConfigurerAdapter {

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

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(100000);// 100k
    return multipartResolver;
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new Hibernate4Module());

    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.dateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"));

    MappingJackson2HttpMessageConverter converter
            = new MappingJackson2HttpMessageConverter(builder.build());

    converter.setObjectMapper(objectMapper);

    converters.add(new ByteArrayHttpMessageConverter());
        converters.add(converter);

    }
}

e

@Configuration
@EnableJpaRepositories("com.aplicacao.thymeleaf.repository")
@EnableTransactionManagement
@PropertySource("classpath:/application.properties")
public class SpringDataConfig {

    @Autowired
    private Environment env;

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory factory) {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(factory);
        manager.setJpaDialect(new HibernateJpaDialect());
        return manager;
    }

    @Bean
    public HibernateJpaVendorAdapter jpaVendorAdapter() {
        HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(env.getProperty("hibernate.show.sql", Boolean.class));
        adapter.setGenerateDdl(env.getProperty("hibernate.ddl", Boolean.class));
        return adapter;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(jpaVendorAdapter());
        factory.setPackagesToScan(
                env.getProperty("hibernate.package.scan"),
                env.getProperty("java.time.jpa.converter")
        );
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUsername(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.pass"));
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        return dataSource;
    }

1 Resposta 1

0

Uma maneira de escrever este bean é da seguinte maneira:

@Configuration
public class ThymeleafEngineConfiguration {

    @Bean
    @ConditionalOnMissingBean(SpringTemplateEngine.class)
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setAdditionalDialects(additionalDialects());
        return engine;
    }

    @Bean
    public Set<IDialect> additionalDialects() {
        Set<IDialect> dialects = new HashSet<>();
        IDialect dialect = new SpringSecurityDialect();
        dialects.add(dialect);
        return dialects;
    }

}

neste link você encontra um exemplo mais detalhado

3
  • Obrigado mas não estou usando o spring-boot !! Poderia me ajudar? Commented 28/04/2017 às 20:45
  • A sim, neste caso tente colocar os dois métodos templateEngine() e additionalDialects() dentro de sua classe ThymeleafConfig
    – brow-joe
    Commented 28/04/2017 às 22:13
  • Pelo que vì no seu código vc tem um método chamado templateEngine() tente colocar neste método o seguinte trecho templateEngine.setAdditionalDialects(additionalDialects()) ai vc precisa só copiar o método additionalDialects() para o seu código
    – brow-joe
    Commented 28/04/2017 às 22:16

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .