2016-06-20 37 views
2

目前,我有以下代碼:如何在沒有屬性文件的情況下使用Spring的@Value?

int port = System.getProperty("port") != null ? 
      Integer.parseInt(System.getProperty("port")) : 
      8080; 

我不喜歡這個,想與Spring替代來取代它。所以,我認爲我應該使用@Value註釋。我不想有這個屬性文件。不過,我想通過註釋獲得默認值。

有沒有辦法做到這一點,沒有屬性文件和正確的代碼實現是什麼?我還需要有PropertySourcesPlaceholderConfigurer嗎?你能告訴我一個如何做到這一點的工作示例嗎?

+0

您能否指定需要春季答案的哪個版本? – tkachuko

+0

4.2.3.RELEASE,我相信....最後一個之前的最後一個。 – carlspring

+1

只需添加'@ PropertySourcesPalceholderConfigurer',添加'@Value(「$ {port:8080}」'。重新啓動並完成。不需要屬性文件即可使用屬性源。如果不使用'@ PropertySourcesPlaceholderConfigurer'你仍然可以使用SpEL,但是這會限制你只能使用系統或環境屬性,並且如果你想有一個回退的話會變得複雜。 –

回答

4

假設你正在使用基於Java的配置。

@Bean 
public static PropertySourcesPlaceholderConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
} 

然後某個字段標註爲@Value

@Value("${port:8080}") 
private int port; 

這將檢查系統屬性和環境給定屬性port。當啓用JNDI時,將檢查並檢查基於servlet的環境,並將其作爲servlet變量。

使用PropertySourcesPlaceholderConfigurer不需要屬性文件,它需要PropertySource s,其中有幾種不同的實現。

如果你不想註冊PropertySourcesPlaceholderConfigurer你可以恢復到SpEL,但這會使它更復雜一些(和醜陋的imho)。

1

我還沒有試過,但你可以使用任何SpEL expression。您的代碼可以被改寫爲:

@Value("#{systemProperties['port'] ?: 8080}") 
private int port; 

請注意,我使用的safe navigation operator

關於PropertySourcesPalceholderConfigurer,我不認爲你需要一個,給你在你的類路徑春節表達語言的依賴性:

<dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-expression</artifactId> 
    <version>4.2.3.RELEASE</version> 
</dependency> 
1

測試和工作。

  1. 是的,你需要PropertyPlaceholderConfigurer但它並不需要的屬性文件
  2. 參考你的系統變量是這樣的:@Value("#{systemEnvironment['YOUR_VARIABLE_NAME'] ?: 'DEFAULT_VALUE'}"

代碼示例:

package abc; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.stereotype.Component; 

@Component 
public class Test { 

    public final String javaPath; 

    @Autowired 
    public Test(@Value("#{systemEnvironment['Path']}") String javaPath) { 
     this.javaPath = javaPath; 
    } 
} 

配置:

@Configuration 
@ComponentScan("abc") 
public class Config { 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 
} 

運行的所有樣本:

public class Runner { 

    public static void main(String[] args) { 
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); 
     Test bean = context.getBean(Test.class); 
     System.out.println(bean.javaPath); 
    } 
} 

希望它能幫助。

相關問題