为什么 spring 中,不支持 autowired 静态变量?
1,557 total views, 3 views today
因为静态变量是属于本身类的信息,当类加载器加载静态变量时,Spring 的上下文环境还没有被加载,所以不可能为静态变量绑定值。
同时,Spring 也不鼓励为静态变量注入值,因为这会增加了耦合度,对测试不友好。但还是有很多方法来绕过这些限制,实现对静态变量注入值。
比如用 set 方法作为跳板,在里面实现赋值。
1 2 3 4 5 6 7 8 9 10 11 |
@Component @PropertySource(value = { "classpath:/mine.properties" }) public class User { public static LogHelper loghelper; @Autowired public void setLoghelper(LogHelper loghelper) { System.out.println("autowired loghelper...."); User.loghelper = loghelper; } } |
或者使用 PostConstruct 当跳板。
1 2 3 4 5 6 7 8 9 10 11 12 |
@Component @PropertySource(value = { "classpath:/mine.properties" }) public class User { public static LogHelper loghelper; @Autowired private LogHelper loghelper1; @PostConstruct public void init() { System.out.println("autowired loghelper...."); User.loghelper = loghelper1; } } |
原创文章,转载请注明出处!http://www.javathings.top/为什么spring中,不支持autowired静态变量?/