gpt4 book ai didi

java - Spring @Bean Name,不适用于@Qualifier

转载 作者:行者123 更新时间:2023-12-04 02:26:52 39 4
gpt4 key购买 nike

我有一个 Spring 启动应用程序。它创建 LocalSessionFactoryBean 对象并注入(inject) session 工厂变量。它工作正常,如下所示:

@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;


@Primary
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan(
new String[] {
"com.abc..entities",
"com.abc.xyz.entities",
"
});
factory.setHibernateProperties(hibernateProperties());
return factory;
}
但是,我需要将 sessionFactory 的 bean 名称(默认为函数名称)从 sessionFactory 更改为 entityManagerFactory,所以我做了以下操作:
  @Autowired
@Qualifier(value="entityManagerFactory")
private SessionFactory sessionFactory;


@Primary
@Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setPackagesToScan(
new String[] {
"com.abc..entities",
"com.abc.xyz.entities",
"
});
factory.setHibernateProperties(hibernateProperties());
return factory;
}
但它会引发错误:
> Error creating bean with name 'XYZ': Unsatisfied dependency expressed
> through field 'sessionFactory'; nested exception is
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type 'org.hibernate.SessionFactory' available:
> expected at least 1 bean which qualifies as autowire candidate.
> Dependency annotations:
> {@org.springframework.beans.factory.annotation.Autowired(required=true),
> @org.springframework.beans.factory.annotation.Qualifier(value=entityManagerFactory)}
我相信我做得对,我在这里错过了什么?
更新 :-
我尝试按照答案之一中提到的方法进行操作,但没有成功:
@Autowired
@Qualifier(value = "entityManagerFactory")
private SessionFactory sessionFactory;
并将方法更改为
@Primary
@Bean

public LocalSessionFactoryBean entityManagerFactory()
{ ..........},


> Unsatisfied dependency expressed through field 'sessionFactory';
> nested exception is
> org.springframework.beans.factory.NoSuchBeanDefinitionException: No
> qualifying bean of type 'org.hibernate.SessionFactory' available:
> expected at least 1 bean which qualifies as autowire candidate.
> Dependency annotations:
> {@org.springframework.beans.factory.annotation.Autowired(required=true),
> @org.springframework.beans.factory.annotation.Qualifier(value=entityManagerFactory)}

最佳答案

我认为这里发生的是 entityManagerFactory 是从 spring 自动为另一个 bean 注册的。因此,您没有得到您所要求的。
试着改一下名字

@Bean(name="customEntityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
进而
@Autowired
@Qualifier("customEntityManagerFactory")
private SessionFactory sessionFactory;

关于java - Spring @Bean Name,不适用于@Qualifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66814195/

39 4 0