| | |
| | | |
| | | |
| | | import org.springframework.beans.factory.annotation.Autowired; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.core.env.Environment; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.annotation.PostConstruct; |
| | | |
| | | @Component |
| | | public class ConfigUtils { |
| | | |
| | | |
| | | private static Environment env; |
| | | // 1. 正常注入非静态字段 |
| | | @Value("${token.secret}") |
| | | private String secret; |
| | | |
| | | @Autowired |
| | | public void setEnv(Environment environment) { |
| | | ConfigUtils.env = environment; |
| | | |
| | | private static ConfigUtils instance; |
| | | |
| | | @PostConstruct |
| | | public void init() { |
| | | instance = this; |
| | | } |
| | | |
| | | public static String getProperty(String key) { |
| | | if (env == null) { |
| | | throw new IllegalStateException("Environment not injected yet"); |
| | | // 3. 提供静态方法供外部调用 |
| | | public static String getMyConfigValue() { |
| | | if (instance == null) { |
| | | throw new IllegalStateException("ConfigUtils has not been initialized by Spring yet."); |
| | | } |
| | | return env.getProperty(key); |
| | | return instance.secret; |
| | | } |
| | | |
| | | public static String getProperty(String key, String defaultValue) { |
| | | if (env == null) { |
| | | return defaultValue; |
| | | // 如果需要修改值,也可以提供静态 setter (视需求而定) |
| | | public static void setMyConfigValue(String value) { |
| | | if (instance != null) { |
| | | instance.secret = value; |
| | | } |
| | | return env.getProperty(key, defaultValue); |
| | | } |
| | | |
| | | } |
| | | |