2017-08-02 87 views
1

所以我为defaultdev并在每个配置中的两个配置有一个春天开机自动装配的EntityManager具体到配置

@Bean 
    @Autowired 
    public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { 
     return entityManagerFactory.createEntityManager(); 
    } 

现在我想在一些组件注入EntityManager像这样

@Autowired 
private EntityManager em; 

但我收到

... required a single bean, but 2 were found: 
    - entityManager: defined by method 'entityManager' in class path resource ... 

为什么EntityManager从默认不注入?

+0

这听起来像二者的配置被加载,不是吗?他们是否受配置文件控制?你打算如何选择只有一个? – DaveyDaveDave

+0

每个配置都有一个@Profile(“...”),同时也设置了活动配置文件。 – Bart

+0

@Bart是否使用'--spring.profiles.active'来提及配置文件? –

回答

2

defaultdev maven个人资料?如果是的话,那么你应该选择的每一个配置的配置与使用@Profile

@Profile("dev") 
@Configuration 
public class DevConfig 

或者,第二种方法 - 标记豆类中的一个作为主:

@Bean 
@Primary 
@Autowired 
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { 
    return entityManagerFactory.createEntityManager(); 
} 
+0

谢谢@尼古拉 – Oleksii