spring@value取不到值的幾種情況


一,spring組件重寫構造方法,在構造方法中引用@value為null

由於spring實例化順序為先執行構造方法,再注入成員變量,所以序為先執行構造方法,再注入成員變量,所以ing實例化順取值為null
解決辦法為:再寫一個常量類,在常量類中引用@value,再在構造方法中引用常量類的變量即可。

二,調用spring組件時使用new對象,而不是@Autowired

三,使用final或static修飾成員變量

四,spring mvc中引用@value為null

spring mvc是spring的子容器,需要在兩個配置文件中都導入配置文件
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

http://blog.51cto.com/jtech/2114686

springboot @ConfigurationProperties @EnableConfigurationProperties 自動配置

通過redis自動配置過程看這兩個注解的聯合使用,達到自動配置
springboot項目,maven

application.properties
配置redis

...
spring.redis.port=7379
...

需要獲取配置的類,比如@Configuration注解的配置類,需要獲取redis配置的其他類,redisProperties.getHost() 就可以取到配置

import org.springframework.boot.autoconfigure.data.redis.RedisProperties

@EnableConfigurationProperties(RedisProperties.class)
class JedisMy{
@Autowired
private RedisProperties redisProperties
}

獲取使用內置的Environment獲取配置,需要指定配置的key,上面的自動配置,key就是類的屬性,redis的配置都是RedisProperties的屬性

import org.springframework.core.env.Environment

class ddd{
@Autowired
private Environment env;

public void dd(){
env.getProperty("spring.redis.port");
}
}
---------------------
作者:qianggetaba
來源:CSDN
原文:https://blog.csdn.net/c5113620/article/details/81383297
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

 

關與 @EnableConfigurationProperties 注解

@EnableConfigurationProperties
測試發現 @ConfigurationProperties@EnableConfigurationProperties 關系特別大。

@EnableConfigurationProperties 文檔中解釋:
@EnableConfigurationProperties注解應用到你的@Configuration時, 任何被@ConfigurationProperties注解的beans將自動被Environment屬性配置。 這種風格的配置特別適合與SpringApplication的外部YAML配置進行配合使用。

測試發現:
1.使用 @EnableConfigurationProperties 進行注冊

@ConfigurationProperties(prefix = "service.properties") public class HelloServiceProperties { private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; set/get } @Configuration @EnableConfigurationProperties(HelloServiceProperties.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true) public class HelloServiceAutoConfiguration { } @RestController public class ConfigurationPropertiesController { @Autowired private HelloServiceProperties helloServiceProperties; @RequestMapping("/getObjectProperties") public Object getObjectProperties () { System.out.println(helloServiceProperties.getMsg()); return myConfigTest.getProperties(); } } 

自動配置設置

service.properties.name=my-test-name
service.properties.ip=192.168.1.1
service.user=kayle
service.port=8080

一切正常,但是 HelloServiceAutoConfiguration 頭部不使用 @EnableConfigurationProperties,測訪問報錯。

2.不使用 @EnableConfigurationProperties 進行注冊,使用 @Component 注冊

@ConfigurationProperties(prefix = "service.properties") @Component public class HelloServiceProperties { private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } 

Controller 不變,一切正常,如果注釋掉 @Component 測啟動報錯。
由此證明,兩種方式都是將被 @ConfigurationProperties 修飾的類,加載到 Spring Env 中。



作者:咪雅先森
鏈接:https://www.jianshu.com/p/7f54da1cb2eb
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。

 

Spring @Value 設置默認值

1. 概述
在 Spring 組件中使用 @Value 注解的方式,很方便的讀取 properties 文件的配置值。

2.使用場景
聲明的變量中使用。

public static class FieldValueTestBean {
 
    @Value("#{ systemProperties['user.region'] }")
    private String defaultLocale;
 
}

setter 方法中

public static class PropertyValueTestBean {
 
    private String defaultLocale;
 
    @Value("#{ systemProperties['user.region'] }")
    public void setDefaultLocale(String defaultLocale) {
        this.defaultLocale = defaultLocale;
    }
 
}

方法中

public class SimpleMovieLister {
 
    private MovieFinder movieFinder;
    private String defaultLocale;
 
    @Autowired
    public void configure(MovieFinder movieFinder,
            @Value("#{ systemProperties['user.region'] }") String defaultLocale) {
        this.movieFinder = movieFinder;
        this.defaultLocale = defaultLocale;
    }
 
    // ...
}

構造方法

public class MovieRecommender {
 
    private String defaultLocale;
 
    private CustomerPreferenceDao customerPreferenceDao;
 
    @Autowired
    public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
            @Value("#{systemProperties['user.country']}") String defaultLocale) {
        this.customerPreferenceDao = customerPreferenceDao;
        this.defaultLocale = defaultLocale;
    }
 
    // ...
}

3. 字符串
字符串類型的屬性設置默認值

@Value("${some.key:my default value}")
private String stringWithDefaultValue;

some.key 沒有設置值,stringWithDefaultValue 變量值將會被設置成 my default value 。
如果默認值設為空,也將會被設置成默認值。

@Value("${some.key:}")
private String stringWithBlankDefaultValue;

 

 


4. 基本類型
基本類型設置默認值。

@Value("${some.key:true}")
private boolean booleanWithDefaultValue;
 
@Value("${some.key:42}")
private int intWithDefaultValue;

包裝類型設置默認值。

@Value("${some.key:true}")
private Boolean booleanWithDefaultValue;
 
@Value("${some.key:42}")
private Integer intWithDefaultValue;

5. 數組
數組的默認值可以使用逗號分割。

@Value("${some.key:one,two,three}")
private String[] stringArrayWithDefaults;
 
@Value("${some.key:1,2,3}")
private int[] intArrayWithDefaults;

 

 

 

 

 

6. SpEL
使用 Spring Expression Language (SpEL) 設置默認值。

下面的代碼標示在systemProperties屬性文件中,如果沒有設置 some.key 的值,my default system property value 會被設置成默認值。

@Value("#{systemProperties['some.key'] ?: 'my default system property value'}")
private String spelWithDefaultValue;

7.結語
上面講解使用 Spring @Value 為屬性設置默認值。在項目中,提供合理的默認值,在大多情況下不用任何配置,就能直接使用。達到零配置的效果,降低被人使用的門檻。簡化新Spring應用的搭建、開發、部署過程。

8.參考鏈接

Using Spring @Value with Defaults

Annotation-based configuration

https://blog.csdn.net/vcfriend/article/details/79700048

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM