0
我通过Spring Boot 1.1.8使用Spring 4,并创建了一个类来缓存一些数据。这个类依赖泛型来工作,但我在Spring中遇到了麻烦,并且在另一个服务中将这个类作为bean自动装配。弹簧4 bean与泛型的自动装配
我得到的错误是这样的:
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [orm.repository.BaseRepository] is defined: expected single matching bean but found 2: dataTypeRepository,propertyNameRepository
类问题:
/**
* The purpose of this class is to get data from a cache backed by a database
* and if it does not exist to create it and insert into the database.
*/
@Service
public class CacheByName<TRepo extends BaseRepository, TItem extends BaseWithName> {
private final TRepo repo;
private final Class<TItem> itemClass;
private final Map<String, TItem> itemsCache; // TODO: change to better caching strategy
@Autowired
public CacheByName(TRepo repo, Class<TItem> itemClass) {
this.repo = repo;
this.itemClass = itemClass;
itemsCache = new HashMap();
}
public TItem getCreateItem(String name) {
TItem item = null;
if(itemsCache.containsKey(name)) {
item = itemsCache.get(name);
} else {
// try and load from db
item = (TItem) repo.findByName(name);
if(item == null) {
try {
item = itemClass.newInstance();
item.setName(name);
repo.saveAndFlush(item);
} catch (InstantiationException | IllegalAccessException ex) {
// TODO: log and handle better
return null;
}
}
itemsCache.put(name, item);
}
return item;
}
}
类BaseRepository扩展JpaRepository如下。其他实际存储库扩展了这一个。
@NoRepositoryBean
public interface BaseRepository<T extends Object, ID extends Serializable> extends JpaRepository<T, ID> {
public T findByName(String name);
}
BaseWithName类是一个MappedSuperclass,它为它定义一个name属性和getters/setters。其他更具体的实体类扩展了这一点。
我想将CacheByName类注入到另一个服务,如下所示。请注意,我定义的实际存储库和实体类的构造函数仿制药:
@Service
public class DataImporter extends BaseImporter {
private static final Logger log = LoggerFactory.getLogger(PropertyImporter.class);
private final PropertyNameRepository propertyNameRepo;
private final CacheByName<DataTypeRepository, DataType> dataTypeCache;
@Autowired
public PropertyImporter(RestTemplate restTemplateD5,
CacheByName<DataTypeRepository, DataType> dataTypeCache) {
super(restTemplateD5);
this.dataTypeCache = dataTypeCache;
}
.
.
.
}
我AppConfig.java如下所示:
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class AppConfig {
@Value("${username}")
private String username;
@Value("${password}")
private String password;
@Bean
public RestTemplate restTemplateD5() {
return RestTemplateFactory.createWithHttpBasicAuth(username, password);
}
}
我一直没能找到多少信息关于创建使用泛型的bean。我怀疑我需要在我的AppConfig中创建另一个@Bean定义,但我无法实现任何有效的工作。
你为什么不干脆usings弹簧'@ Cacheable'支持呢?只需添加注释和宾果,缓存... – 2014-11-14 15:05:20
是的谢谢 - 我打算将来使用它,但我的问题是关于bean实例化,而不是缓存方面。 – Hamish 2014-11-14 15:26:47