2013-01-01 58 views
1

我有一个使用外部库的Spring MVC,我无法访问代码。这个外部库使用标准的system.getProperty调用来读取一些属性。我必须在使用该服务之前设置这些值。Spring MVC - 在控制器上设置初始化属性

由于我的应用程序是一个Spring MVC应用程序,我不知道如何初始化这些属性。这是我迄今为止所做的,但由于某些原因,我的值始终为空。

我把一个属性的属性文件/conf/config.properties

my.user=myuser 
my.password=mypassowrd 
my.connection=(DESCRIPTION=(LOAD_BALANCE=on)(ADDRESS=(PROTOCOL=TCP)(HOST=xxxx.xxxx.xxxx)(PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=xxx.xxx.xxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=myService))) 

我加入以下两行我applicationContext.xml

<context:annotation-config/> 
<context:property-placeholder location="classpath*:conf/config.properties"/>  

我阅读文档是设置了初始化代码,你可以实现InitializingBean接口,所以我实现了接口并实现了afterPropertiesSet()方法。

private static @Value("${my.user}") String username; 
private static @Value("${my.password}") String password; 
private static @Value("${my.connection}") String connectionString; 

@Override 
    public void afterPropertiesSet() throws Exception {  
     System.setProperty("username",username); 
     System.setProperty("password",password); 
     System.setProperty("connectionString",connectionString); 
    } 

问题是,调用afterPropertiesSet()方法时,这些值始终为空。

  • 上述方法是否正确初始化代码,尤其是对于控制器?如果第二次打电话给控制器会发生什么?
  • 由于初始化,值是否为空?即春天还没有设置他们呢?
  • 是否可以添加远离控制器的初始化代码?

回答

2

你肯定你的bean /控制器的定义是相同的弹簧背景下的配置文件,你必须在property-placeholder定义是什么?

看一看鲍里斯这个问题的答案:Spring @Value annotation in @Controller class not evaluating to value inside properties file

如果你想从你的控制器移动你的代码,你可以添加监听当春天已经完成初始化一个组件,和母鸡调用代码:

@Component 
public class ApplicationStartedListener implements ApplicationListener<ContextRefreshedEvent> { 

    private static @Value("${my.user}") String username; 
    private static @Value("${my.password}") String password; 
    private static @Value("${my.connection}") String connectionString; 

    public void onApplicationEvent(ContextRefreshedEvent event) { 
     System.setProperty("username",username); 
     System.setProperty("password",password); 
     System.setProperty("connectionString",connectionString); 
    } 
} 
+0

我只有一个applicationContext.xml文件位于WEB-INF文件夹中。 System.setProperty调用都在Controller的无参数构造函数中。也许这就是导致问题的原因。 – ziggy

+0

@ziggy我从你的问题中假设所有的@Value变量都是null。你是说他们的值是正确地从配置文件填充的,但是'System.setProperty()'没有设置值? –

+0

不,你是正确的,因为@Value值从未设置,因此它们在到达System.setProperty调用之前为空。 – ziggy

1

的修复应该是相当简单的,只是从你的领域,那么AutoWiredAnnotationPostProcessor负责与@AuotWired@Value注释字段注入去除static修改,将能够在注入的CORRE价值ctly和你的afterPropertiesSet应该被打电话干净地

+0

这似乎并没有解决它。使用静态变量是错误的,所以我将它们更改为实例变量,但属性仍为空。 – ziggy