编程语言
首页 > 编程语言> > java-Config.class中的CacheManager bean定义导致NoSuchBeanDefinitionException

java-Config.class中的CacheManager bean定义导致NoSuchBeanDefinitionException

作者:互联网

我有一个正在检查数据库条目的Spring服务.为了最大程度地减少我的存储库调用,两个查找方法都是“ @Cacheable”.但是,当我尝试在配置类具有CacheManager bean定义时初始化服务bean时,出现以下NoSuchBeanDefinitionException:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'foo.mediacode.directory.MediaCodeDirectoryService' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:353)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:340)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1093)
at foo.mediacode.directory.MediaCodeDirectoryService.implementation(MediaCodeDirectoryService.java:63)
at foo.campaigntree.directory.CampaignTreeDirectoryService.<init>(CampaignTreeDirectoryService.java:18)
... 15 more

如果删除CacheManager bean定义,则可以初始化我的服务bean,它可以毫无问题地进行缓存并运行!

这是我的代码:
组态

...
    @Configuration
    @EnableCaching
    @EnableJpaRepositories(...)
    @PropertySource({...})
    public class MediaCodeDirectoryServiceConfig {

        private static Logger   configLogger    = Logger.getLogger(MediaCodeDirectoryServiceConfig.class.getName());

        @Value("${jpa.loggingLevel:FINE}")
        private String          loggingLevel;

        @Value("${mysql.databaseDriver}")
        private String          dataBaseDriver;

        @Value("${mysql.username}")
        private String          username;

        @Value("${mysql.password}")
        private String          password;

        @Value("${mysql.databaseUrl}")
        private String          databaseUrl;

        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
            ...
        }

        @Bean
        public MediaCodeDirectoryService mediaCodeDirectoryService() {
            return new MediaCodeDirectoryService();
        }

        @Bean
        public CacheManager mediaCodeCacheManager() {
            SimpleCacheManager cacheManager = new SimpleCacheManager();
            cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("mediaCodeMappingRegexCache"),
                    new ConcurrentMapCache("mediaCodeMappingsCache")));

            return cacheManager;
        }

        @Bean
        public JpaTransactionManager transactionManager() {
            ...
        }

        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
            ...
        }

        public DataSource getDataSource() {
            ...
        }

        public JpaDialect getJpaDialect() {
            ...
        }

        public Properties getEclipseLinkProperty() {
            ...
        }

        public JpaVendorAdapter getJpaVendorAdapter() {
            ...
        }
    }

服务

....
    public class MediaCodeDirectoryService implements MediaCodeDirectoryServiceApi {

        ...

        @Autowired
        private MediaCodeDirectoryRepository repo;

        @SuppressWarnings("resource")
        public static MediaCodeDirectoryServiceApi implementation() {
        if (INSTANCE == null) {
                ApplicationContext ctx = new AnnotationConfigApplicationContext(MediaCodeDirectoryServiceConfig.class);
                INSTANCE = ctx.getBean(MediaCodeDirectoryService.class);
            }

            return INSTANCE;
        }
...

资料库

...
@Repository
public interface MediaCodeDirectoryRepository extends CrudRepository<MediaCodeDao, Integer> {

    @Cacheable("mediaCodeMappingRegexes")
    @Query("SELECT m FROM  #{#entityName} m WHERE (m.fooId = :fooId) AND (m.isRegex = :isRegex) ORDER BY (m.orderId DESC, m.id ASC)")
    List<MediaCodeDao> findByfooIdAndIsRegexOrderByOrderIdDescAndIdAsc(@Param("fooId") int fooId, @Param("isRegex") boolean isRegex);

    @Cacheable("mediaCodeMappings")
    List<MediaCodeDao> findByMediaCode(String MediaCode, Pageable pageable);
}

当我调试到DefaultListableBeanFactory时,可以在beanDefinitionMap中找到我的mediaCodeDirectoryService,也可以在beanDefinitionNames中找到mediaCodeDirectoryService.但是DefaultListableBeanFactory.getBean(…)无法解析名称,第364行中的namedBean为空.

当我尝试通过String获取上下文时,例如:

INSTANCE = (MediaCodeDirectoryService) ctx.getBean("mediaCodeDirecotryService")

我避免了NoSuchBeanDefinitionException,但是遇到了另一个.

这里的任何人都有可能是什么原因的想法?我是否错过了配置中的某些内容?谢谢!

解决方法:

缓存是通过AOP应用的.对于AOP,Spring使用基于代理的方法,默认设置是创建基于接口的代理.

public class MediaCodeDirectoryService implements MediaCodeDirectoryServiceApi {... }

在运行时使用该类定义,您将获得一个动态创建的类(Proxy $51或类似的东西),该类实现所有接口,但它不是MediaCodeDirectoryService.但是,它是MediaCodeDirectoryServiceApi.

您有2种解决此问题的方法,一种是将程序编程到接口(因为您已经定义了接口,所以应该一直这样做),而不是具体的类,或者使用基于类的代理.

第一个选项涉及直接在@Autowire的位置中更改代码,或者获取MediaCodeDirectoryService的实例以改为使用MediaCodeDirectoryServiceApi(我应该做的,为什么还要定义一个接口).现在,您将注入代理,一切正常.

第二个选项涉及在@EnableCaching批注上设置proxyTargetClass = true.然后,您将获得基于类的代理,而不是基于接口的代理.

@EnableCaching(proxyTargetClass=true)

标签:spring-cache,spring-data-jpa,eclipselink,java
来源: https://codeday.me/bug/20191026/1933097.html