2014-12-22 168 views
3

我正在使用Spring框架(版本3.2),并且在我的应用程序中进行了一些重构之后,我遇到了使用Profile配置进行自动装配的问题。Spring @配置文件和自动装配匹配

假设我有一个由两个类实现的接口。这些类根据环境设置实现一堆方法。其实我有3个不同的配置文件属性profile1,profile2和profile3。使用配置文件效果很好,但这是我第一次遇到小问题,因为找不到2个候选人,所以无法注入课程。

public interface Iexample { 
    public void doSomething(); 
} 

@Profile("profile1") 
public class classA implements Iexample { 
    doSomething(){..} 
} 

@Profile("{profile2, profile3}")  
public class ClassB implements Iexample { 
    doSomething(){..} 
} 

public class Test1 { 

@Autowired 
Iexample example; //Should use implementation based on profile1 or profile2 

} 

public class Test2 { 

@Autowired 
Iexample example; //Should use implementation based on profile3 only 

} 
配置

Current属性:

spring.profiles.active= profile1,profile3 

可能配置

  • 配置文件1,Profile3的
  • PROFILE2,Profile3的

任何方式来指定哪些S级应该在任何情况下实施(像@Qualifier)?

为什么不用@ActiveProfiles?

ActiveProfiles是用于声明 ,其活性bean定义分布应当为测试类加载 ApplicationContext中时使用的类级注释。

在这种情况下,我需要知道是否有任何方法可以指示哪些类取决于配置文件应该注入。

请看下面的例子。

@Controller 
public class exampleController { 
    @Autowired 
    // Suppose that this can be possible 
    @Qualifier("{profile1, profile2}") 
    Iexample example 
} 

如果以这种方式指定的限定符可能会工作,那么我将能够解决这个问题。

感谢

+0

用@ActiveProfiles注释您的测试用例 –

+0

我已更新关于您的评论的问题。 –

回答

0

您可以标记与@Primary注解的bean来指定,它应该享有优先权自动装配候选人。 javadoc适用于Spring 4,但Spring 3.2的文档也提到了注释。

+0

我考虑过使用@Primary注解,但是在某些情况下,我无法确定哪些实现可以是默认的。当我完全确定我需要的是在注入接口的类中的唯一地方。请看看Test1和Test2的评论。 无论如何感谢提示。 –