java Java的:春季:Java的配置:样品

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Java的:春季:Java的配置:样品相关的知识,希望对你有一定的参考价值。

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * http://static.springsource.org/spring-framework/docs/3.2.0.RELEASE/spring-framework-reference/html/mvc.html#mvc-container-config
 *
 * @author Geoffroy Warin (https://github.com/geowarin)
 */
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{

  @Override
  protected Class<?>[] getRootConfigClasses()
  {
    return new Class<?>[] { JpaConfig.class, AspectConfig.class, CacheConfig.class,
            MailConfig.class, MongoConfig.class, SecurityConfig.class };
  }

  @Override
  protected Class<?>[] getServletConfigClasses()
  {
    return new Class<?>[] { WebConfig.class };
  }

  @Override
  protected String[] getServletMappings()
  {
    return new String[] { "/" };
  }
  
  /*
  @Override
  protected Filter[] getServletFilters() {
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    return new Filter[] { characterEncodingFilter, new SiteMeshFilter()};
  }
  */
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {
  "foo.bar.controller",
})
public class WebConfig extends WebMvcConfigurerAdapter
{

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

  @Override
  public void addInterceptors(InterceptorRegistry registry)
  {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    registry.addInterceptor(localeChangeInterceptor);
  }

  @Bean
  public LocaleResolver localeResolver()
  {

    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
    cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en"));
    return cookieLocaleResolver;
  }

  @Bean
  public ViewResolver viewResolver()
  {

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
  }

  @Bean
  public MultipartResolver multipartResolver()
  {
    return new CommonsMultipartResolver();
  }

  @Bean
  public MessageSource messageSource()
  {

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
    // if true, the key of the message will be displayed if the key is not
    // found, instead of throwing a NoSuchMessageException
    messageSource.setUseCodeAsDefaultMessage(true);
    messageSource.setDefaultEncoding("UTF-8");
    // # -1 : never reload, 0 always reload
    messageSource.setCacheSeconds(0);
    return messageSource;
  }

  @Bean
  public ApplicationContextProvider getApplicationContext()
  {
    return new ApplicationContextProvider();
  }

  /**
   * Returns a request interceptor for adding Parse authentication
   * headers to Parse requests
   */
  @Bean
  public ClientHttpRequestInterceptor getRequestInterceptor()
  {
    return new ParseApiRequestInterceptor();
  }
}
// package ...
// imports

@Configuration
@ComponentScan(basePackages = {
  "foo.bar.controller.aspects",
  "foo.bar.service",
  "foo.bar.util"
})
@EnableJpaRepositories("foo.bar.repository")
@EnableTransactionManagement
@Import(AppConfig.class)
public class JpaConfig implements TransactionManagementConfigurer
{

  private
  @Value("${jdbcProperties.url}")
  String jdbcUrl;
  private
  @Value("${jdbcProperties.username}")
  String username;
  private
  @Value("${jdbcProperties.password}")
  String password;

  // BoneCP properties
  @Value("${jdbcProperties.bonecp.idleConnectionTestPeriod}")
  private int idleConnectionTestPeriod;

  @Value("${jdbcProperties.bonecp.idleMaxAge}")
  private int idleMaxAge;

  @Value("${jdbcProperties.bonecp.maxConnectionsPerPartition}")
  private int maxConnectionsPerPartition;

  @Value("${jdbcProperties.bonecp.minConnectionsPerPartition}")
  private int minConnectionsPerPartition;

  @Value("${jdbcProperties.bonecp.partitionCount}")
  private int partitionCount;

  @Value("${jdbcProperties.bonecp.acquireIncrement}")
  private int acquireIncrement;

  @Value("${jdbcProperties.bonecp.statementsCacheSize}")
  private int statementsCacheSize;

  @Value("${jdbcProperties.bonecp.releaseHelperThreads}")
  private int releaseHelperThreads;

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory()
  {
    HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();

    LocalContainerEntityManagerFactoryBean lcemfb
            = new LocalContainerEntityManagerFactoryBean();

    lcemfb.setDataSource(this.dataSource());
    lcemfb.setPersistenceProvider(new HibernatePersistenceProvider());
    lcemfb.setPackagesToScan(new String[] { "au.com.nymet.model" });
    lcemfb.setPersistenceUnitName("WaterMePU");
    lcemfb.setJpaVendorAdapter(va);

    Properties ps = new Properties();
    ps.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
    // ps.put("hibernate.hbm2ddl.auto", "validate");
    ps.put("hibernate.hbm2ddl.auto", "update");
    ps.put("hibernate.connection.release_mode", "after_transaction");

    ps.put("hibernate.max_fetch_depth", 3);
    // ps.put("hibernate.ejb.use_class_enhancer", true); // For lazy one-to-one owner loading, but should be in an ejb container

    // ps.put("hibernate.show_sql", true); // Already enabled in log4j.properties
    // ps.put("hibernate.format_sql", true);
    ps.put("hibernate.use_sql_comments", true);

    lcemfb.setJpaProperties(ps);
    lcemfb.afterPropertiesSet();
    return lcemfb;
  }

  @Bean
  public DataSource dataSource()
  {
    /*
    DriverManagerDataSource ds = new DriverManagerDataSource();
        
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl(jdbcUrl);
    ds.setUsername(username);
    ds.setPassword(password);
        
    return ds;
    */

    LazyConnectionDataSourceProxy proxy = new LazyConnectionDataSourceProxy(bonecpDataSource());
    return proxy;
  }

  @Bean
  public DataSource bonecpDataSource()
  {
    BoneCPDataSource ds = new BoneCPDataSource();

    ds.setDriverClass("com.mysql.jdbc.Driver");
    ds.setJdbcUrl(jdbcUrl);
    ds.setUsername(username);
    ds.setPassword(password);

    ds.setIdleConnectionTestPeriod(idleConnectionTestPeriod, TimeUnit.MINUTES);
    ds.setIdleMaxAge(idleMaxAge, TimeUnit.MINUTES);
    ds.setMaxConnectionsPerPartition(maxConnectionsPerPartition);
    ds.setMinConnectionsPerPartition(minConnectionsPerPartition);
    ds.setPartitionCount(partitionCount);
    ds.setAcquireIncrement(acquireIncrement);
    ds.setStatementsCacheSize(statementsCacheSize);
    ds.setReleaseHelperThreads(releaseHelperThreads);

    return ds;
  }

  @Bean
  public PlatformTransactionManager transactionManager()
  {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(this.entityManagerFactory().getObject());
    return tm;
  }

  @Override
  public PlatformTransactionManager annotationDrivenTransactionManager()
  {
    return transactionManager();
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
  {
    return new PersistenceExceptionTranslationPostProcessor();
  }
}

以上是关于java Java的:春季:Java的配置:样品的主要内容,如果未能解决你的问题,请参考以下文章

在春季使用 JSR310 java.time 时将日期、即时序列化为 ISO 8601

Java 类强制转换异常 - 春季启动

备战2022年春季面试Java基础面试题库《收藏》

xml Java的:春季:CONFIG.XML

春季迁移后,带有“java.util.logging”的Tomcat日志停止工作

java 春季启动服务样本