月度归档: 2015 年 2 月

  • Spring根据包名搜索类

    有时候我们会遇到这种情况,需要根据动态获取某个包下的一些特定类。

    比如获取”com.xxx.domain”下所有类。

    Spring中ClassPathScanningCandidateComponentProvider可以快速完成这项任务。

    Spring最核心的一个部分就是Ioc,通过@Component来注解需要委托管理的类。

    ClassPathScanningCandidateComponentProvider提供了一个默认的过滤器来处理Component。

    protectedvoidregisterDefaultFilters() {
    this.includeFilters.add(new AnnotationTypeFilter(Component.class));
    ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();
    try {
    this.includeFilters.add(new AnnotationTypeFilter(((Class < ?extends Annotation > ) ClassUtils.forName("javax.annotation.ManagedBean", cl)),false));
    logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");
    }catch(ClassNotFoundException ex) {
    // 
  • Spring Boot获取Active Profile的值

    Spring Boot提供了profile机制,可以快速的在不同情况下切换配置。

    默认支持很多配置,从Spring整体的行为到具体的数据库,渲染引擎的行为都有支持。按照文档给出的配置名称和可选值操作就可以了。

    有些时候我们需要基于profile来实现自己的一些配置,这个时候就需要自己完成一些后面的细节了。

    举个比较常见的例子,profile分为了dev和prod两种。而项目本身需要支持上传图片功能,需要在profile中指定文件配置,比如

    upload.path=C:Users315junAppDataLocalTemp

    要获取这个值,我们有三种办法

    • 从Env中读取
    @Autowired
    private Environment env;
    String path=env.getProperty("upload.path");
    • 构造一个Config类,通过注解自动注入
    @ConfigurationProperties(prefix ="upload")
    publicclass UpdatePathConfig {
    private String path;
    
    public StringgetPath() {
    return path;
    }
    
    publicvoidsetPath(String path) {
    this.path = path;
    }
    }
    • 通过Value注解注入
      这种方法最直接,在对应的字段上标注即可。
    @Value("${upload.path}")
    
  • Spring Boot 中文乱码问题

    Spring Boot默认的编码并不是UTF8,在一些表单中中文会有乱码的情况,需要添加一个Filter来解决。

    Spring Boot大量使用注解,而不是xml配置文件,所以我们的Filter也使用Java-base的配置模式。

    @Beanpublic FiltercharacterEncodingFilter() {
      CharacterEncodingFilter characterEncodingFilter =new CharacterEncodingFilter();
      characterEncodingFilter.setEncoding("UTF-8");
      characterEncodingFilter.setForceEncoding(true);
      return characterEncodingFilter;
    }

    相关文章:

    再谈Spring Boot中的乱码和编码问题

    网站乱码和ISO-8859-1与UTF-8

     …