gpt4 book ai didi

java - Spring Autowiring 参数化类的问题

转载 作者:行者123 更新时间:2023-11-30 03:47:19 25 4
gpt4 key购买 nike

我已经被这个问题困扰了一段时间,并且浏览了很多文章,但无法找到解决方案。感谢您对以下问题的帮助。

我需要能够在服务类中 Autowiring EntityManager,但会引发异常。由于类型删除,默认构造函数可能存在问题,因此我尝试使用带参数的构造函数来设置类型。如何 Autowiring User 类型的 EntityManager?

public interface IEntityManager<T extends IDomain<ID>, ID extends Serializable> {

T findById(ID id, boolean lock);

T save(T entity);

void delete(T entity);
}

public class EntityManager<T extends IDomain<ID>, ID extends Serializable>
implements IEntityManager<T, ID> {

private Class<T> entity;

@Autowired(required=true)
private SessionFactory sessionFactory;

/*
@SuppressWarnings("unchecked")
public EntityManager() {
this.entity = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];

} */

@Autowired(required=true)
public EntityManager(Class<T> entity) {
this.entity = entity;
}
}

@Service("UserService")
@Transactional
public class UserServiceImpl implements IUserService {

@Autowired
EntityManager<User, Integer> entityManager;
}

这是一个异常(exception):

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'UserService': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.test.dummy.persistence.manager.EntityManager com.test.dummy.service.UserServiceImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.test.dummy.persistence.manager.EntityManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)

最佳答案

Spring 无法推断出它需要注入(inject) User.classEntityManager 的构造函数中满足UserServiceImpl中的依赖关系。

如果您使用Spring 4,您可以定义 EntityManager<User, Integer> 类型的 bean :

@Configuration
public class Config {
@Bean
public EntityManager<User, Integer> userEntityManager() {
new EntityManager(User.class);
}
}

编辑:或者定义一个BeanDefinitionRegistryPostProcessor它将检查需要 EntityManager 作为依赖项的 bean,识别所需的类型,为所需类型构造新的 EntityManager bean 并将其添加到 bean 注册表中。

 @Component
public class MyEntityManagerBeanDefinitionRegistryPostProcessor implements
BeanDefinitionRegistryPostProcessor {


@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory)
throws BeansException {
for (String beanName : beanFactory.getBeanDefinitionNames()) {
final BeanDefinition beanDefinition = getOriginatingBeanDefinition(
beanFactory.getBeanDefinition(beanName));
final Class<?> beanClass = getClass(beanDefinition.getBeanClassName());
if (beanClass != null) {
ReflectionUtils.doWithFields(beanClass, new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

if (field.isAnnotationPresent(Autowired.class) || field.isAnnotationPresent(
Inject.class)) {
if (field.getGenericType() instanceof ParameterizedType) {
final ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
final Class<?> rawType = (Class) parameterizedType.getRawType();
if (rawType.equals(EntityManager.class)) {
final Class<?> typeArgument = (Class<?>) parameterizedType.getActualTypeArguments()[0];
beanFactory.registerSingleton(field.getName(), new EntityManager(typeArgument));
}
}
}
}
});
}
}
}

private Class<?> getClass(String className) throws BeansException {
if (className != null) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new BeanInitializationException("beanClass not found", e);
}
}
return null;
}

private BeanDefinition getOriginatingBeanDefinition(BeanDefinition beanDefinition) {
while(beanDefinition.getOriginatingBeanDefinition() != null) {
beanDefinition = beanDefinition.getOriginatingBeanDefinition();
}
return beanDefinition;
}


@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { }
}

最后,看起来您真正需要的是使用 Spring Data Jpa从本质上讲,它允许您通过定义如下接口(interface)来定义参数化 DAO:

package com.myapp.repository; 

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

您启用它:

@Configuration
@EnableJpaRepositories(basePackages = "com.myapp.repository")
public class Config {


}

然后您注入(inject) UserRepository :

@Autowired
private UserRepository userRepository;

Spring 将注入(inject)一个基本的 DAO 实现。

关于java - Spring Autowiring 参数化类的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25331213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com