深入解读springboot使用注解@value注入static变量
背景
使用springboot的过程中,比较方便的一个功能就是变量注入,使用@value注解,就可以简单的将配置文件中的变量注入到代码中。
但是使用过程,发现一个问题,@value对于static变量的支持不太好,所以本文就研究了一下怎么注入static变量。
开始解决问题
1.简单的静态变量@value注入示例
(1)A类(定义静态变量注入属性值)
在这个类中,我们将属性"jdbc.url"的值注入到了MyComponent类中定义的静态变量"url"中。这样就简单的完成了
注意setUrl方法不能是static
@Component
public class MyComponent {
public static String url;
@Value("${jdbc.url}")
private void setUrl(String url) {
MyComponent.url = url;
}
}
2.如果该变量需要被其他类,在static代码块中引用呢?
(2)B类(通过静态块引用 A 类的代码块)
在这个类中,我们使用静态块来引用A类的静态变量"url"。
@Component
public class AnotherComponent {
static {
// 静态块内访问A类的静态变量
System.out.println(MyComponent.url);
}
}
(3)保证A、B类的实例化先后顺序
SpringBoot启动类(注入A类的实例,并确保A类在B类之前初始化):
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private MyComponent myComponent;
@Autowired
private AnotherComponent anotherComponent;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
// 这里可以访问MyComponent的实例和AnotherComponent的静态代码块
}
}