SpringBoot项目的参数配置轻便性,springframework提供@Value取参数的注解,最近在项目中使用中发现,@Value注解对static修饰的对象无效,查了资料发现确实不支持。
解决方法一:
给要赋值的对象添加一个setter方法,当然这个对象所在的类需要被Spring管理,所以需要添加Spring的注解,我这里添加的是组件注解@Component,具体代码如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SystemConfigUtil {
public static String rootPath;
public static String loginPath;
public static String applicationName;
@Value("${sys.root.path}")
public static void setRootPath(String rootPath) {
SystemConfigUtil.rootPath = rootPath;
}
@Value("${sys.login.path}")
public static void setLoginPath(String loginPath) {
SystemConfigUtil.loginPath = loginPath;
}
@Value("${spring.application.name}")
public static void setApplicationName(String applicationName) {
SystemConfigUtil.applicationName = applicationName;
}
}
解决方法二:
使用InitializingBean在容器配置文件初始完后就进行赋值,具体代码如下:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class SystemConfigUtil implements InitializingBean {
public static String rootPath;
public static String loginPath;
public static String applicationName;
@Value("${sys.root.path}")
private String root_path;
@Value("${sys.login.path}")
private String login_path;
@Value("${spring.application.name}")
private String application_name;
@Override
public void afterPropertiesSet() throws Exception {
rootPath = root_path;
loginPath = login_path;
applicationName = application_name;
}
}