版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z28126308/article/details/81289388
解决方法: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; }