一、使用@ConfigurationProperties
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtConfig {
private String encryptAESKey;
private String encryptJWTKey;
private String tokenExpireTime;
}
二、使用@Value
@Data
@Component
public class JwtConfig {
@Value("${jwt.encryptAESKey}")
private String encryptAESKey;
@Value("${jwt.encryptJWTKey}")
private String encryptJWTKey;
@Value("${jwt.tokenExpireTime}")
private String tokenExpireTime;
}
三、使用Environment
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
private Environment env;
@RequestMapping("test2")
public void test2() {
String encryptAESKey = env.getProperty("jwt.encryptAESKey");
String encryptJWTKey = env.getProperty("jwt.encryptJWTKey");
String tokenExpireTime = env.getProperty("jwt.tokenExpireTime");
}
}
四、使用PropertiesLoaderUtils
通过注册监听器(Listeners) + PropertiesLoaderUtils的方式
配置文件类
/**
* 配置文件类
*/
public class PropertiesListenerConfig {
public static Map<String, String> propertiesMap = new HashMap<>();
private static void processProperties(Properties props) throws BeansException {
propertiesMap = new HashMap<>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
try {
// PropertiesLoaderUtils的默认编码是ISO-8859-1,需转码
propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
public static void loadAllProperties(String propertyFileName) {
try {
Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
processProperties(properties);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
}
public static Map<String, String> getAllProperty() {
return propertiesMap;
}
}
监听器
/**
* 配置文件监听器,用来加载自定义配置文件
*/
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
private String propertyFileName;
public PropertiesListener(String propertyFileName) {
this.propertyFileName = propertyFileName;
}
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
PropertiesListenerConfig.loadAllProperties(propertyFileName);
}
}
注册监听器、获取配置
@SpringBootApplication
public class Applaction {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Applaction.class);
// 注册监听器
application.addListeners(new PropertiesListener("jwt.properties"));
application.run(args);
// 获取配置
Map<String, String> map = PropertiesListenerConfig.getAllProperty();
}
}