@Autowired
@Component
public class MyComponent {
private static String myStaticVariable;
private static ApplicationContext applicationContext;
@Autowired
public void setApplicationContext(ApplicationContext context) {
MyComponent.applicationContext = context;
}
public static void setMyStaticVariable(String value) {
myStaticVariable = value;
}
public static void doSomething() {
// 使用静态变量进行操作
System.out.println(myStaticVariable);
}
public static void main(String[] args) {
// 获取ApplicationContext实例
MyComponent.applicationContext.getBean(MyComponent.class).setMyStaticVariable("Hello World");
MyComponent.doSomething();
}
}
@Value
@Component
public class MyComponent {
private static String myStaticVariable;
@Value("${myapp.my-static-variable}")
public void setMyStaticVariable(String value) {
myStaticVariable = value;
}
public static void doSomething() {
// 使用注入的静态变量进行操作
System.out.println(myStaticVariable);
}
}