2013-04-04 78 views
3

我有以下控制器定义:用SpringMVC:变量在注释

@Controller 
@RequestMapping("/test") 
public class MyController extends AbstractController 
{ 

    @Autowired 
    public MyController(@Qualifier("anotherController") AnotherController anotherController)) 
    { 
    ... 
    } 

} 

我不知道是否有可能在@Qualifier注解使用变量,这样我可以注入不同的.properties文件不同的控制器如:

@Controller 
@RequestMapping("/test") 
public class MyController extends AbstractController 
{ 

    @Autowired 
    public MyController(@Qualifier("${awesomeController}") AnotherController anotherController)) 
    { 
    ... 
    } 

} 

每当我尝试,我得到:

org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No matching bean of type [com.example.MyController] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this 
dependency. Dependency annotations: 
{@org.springframework.beans.factory.annotation.Qualifier(value=${awesomeController}) 

我已经包括d我的config.xml文件下面bean:

<bean id="propertyConfigurer" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
     <list> 
      <value>classpath:config/application.properties</value> 
     </list> 
    </property> 
</bean> 

但豆不起作用,除非我在XML文件中显式声明的bean。

我该怎么做注释?

+0

http://stackoverflow.com/questions/317687/how-can-i-inject-a-property-value-into-a-spring-bean-which-was-configured-using和http:// springinpractice 。COM/2008/12/02 /新的东西,在弹簧-30/ – NimChimpsky 2013-04-04 16:02:00

回答

2

首先,我认为依赖注入依赖于配置属性是不好的做法。试图做到这一点你可能会走错方向。

但是要回答您的问题:访问placeHolder属性需要依赖注入完成。为了确保它,您可以将您的代码访问@PostContruct带注释的方法中的属性。

您将需要使用getBean()方法手动从applicationContext中检索bean。

@Value("${awesomeController}") 
private String myControllerName; 

@PostConstruct 
public void init(){ 
    AnotherController myController = (AnotherController) appContext.getBean(myControllerName); 
} 
+0

我试图@ PostContruct的构造,但是这是一个无效的批注的位置,所以我创建了一个setter方法: @ PostConstruct @自动装配Autowired 公共无效集( @预选赛( “$ {} awesomeController”)anotherController anotherController) { ... } 但我发现了以下错误: java.lang.IllegalStateException:生命周期方法注释需要一个没有-arg方法 你能详细解释一下吗? – Jason 2013-04-04 13:50:58

+0

我编辑了我的答案来展示一个例子。 – kgautron 2013-04-04 13:57:04

1

我不知道你在做什么是可能的,但我可以提出一个稍微不同的方法,但前提是你使用Spring 3.1+。你可以尝试使用Spring Profiles。

定义要在不同的控制器,每个配置文件之一:

<beans> 
    <!-- Common bean definitions etc... --> 

    <beans profile="a"> 
     <bean id="anotherController" class="...AnotherController" /> 
    </beans> 

    <beans profile="b"> 
     <!-- Some other class/config here... --> 
     <bean id="anotherController" class="...AnotherController"/> 
    </beans> 
</beans> 

您的控制器将失去@Qualifier,成为类似:

@Autowired 
public MyController(AnotherController anotherController) { 
    ... 
} 

然后在运行时,你可以指定哪些控制器豆你想要通过使用系统属性激活相应的配置文件来使用,例如:

-Dspring.profiles.active="a" 

或:

-Dspring.profiles.active="b" 

它可能会设定一个基于属性文件的配置文件,但你可以从this post在春季博客找到更多关于Spring配置文件。我希望这有所帮助。