1. 程式人生 > >踩坑記2018-7-30A:SpringCloud下@ConfigurationProperties屬性注入無效解決

踩坑記2018-7-30A:SpringCloud下@ConfigurationProperties屬性注入無效解決

解決方法:Bean的生成方法上添加註解@RefreshScope(也可新增到配置類上),關聯的配置類也需新增

範例如下:

@Configuration
@EnableAutoConfiguration
public class DataSourceConfig {

    @Bean
    @RefreshScope
    @ConfigurationProperties(prefix = "jdbc")
    public DruidDataSource dataSource() {
        return new DruidDataSource();
    }
}

由於sessionFactory也呼叫了dataSource,所以該bean也需新增@RefreshScope

@Configuration
public class MybatisConfig {
@Bean("sqlSessionFactory")
@RefreshScope
public MybatisSqlSessionFactoryBean sqlSessionFactory(MybatisConfiguration mybatisConfiguration,
                                                      DataSource dataSource,
                                                      GlobalConfiguration globalConfig) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    sqlSessionFactory.setMapperLocations(resourcePatternResolver.getResources(MAPPER_PATH));
    sqlSessionFactory.setTypeAliasesPackage(MODEL_PACKAGE);
    sqlSessionFactory.setConfiguration(mybatisConfiguration);
    sqlSessionFactory.setPlugins(new Interceptor[]{
            new PaginationInterceptor(),
            new PerformanceInterceptor(),
            new OptimisticLockerInterceptor(),
            createPageInterceptor()
    });
    sqlSessionFactory.setGlobalConfig(globalConfig);
    return sqlSessionFactory;
}

}

迴歸看RefreshScope作用:

被該方式註解的所有類可以在執行時被重新整理,及所有使用到這些類的component將在下一個方法呼叫中獲得新的例項,完全初始化並注入所有依賴項。該註解一般用於靜態檔案配置類中,該註解具體的官方地址:http://springcloud.cn/view/251

/**
 * Convenience annotation to put a <code>@Bean</code> definition in
 * {@link org.springframework.cloud.context.scope.refresh.RefreshScope refresh scope}.
 * Beans annotated this way can be refreshed at runtime and any components that are using
 * them will get a new instance on the next method call, fully initialized and injected
 * with all dependencies.
 * 
 * @author Dave Syer
 *
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Scope("refresh")
@Documented
public @interface RefreshScope {
   /**
    * @see Scope#proxyMode()
    */
   ScopedProxyMode proxyMode() default ScopedProxyMode.TARGET_CLASS;

}