首页 文章
取消

Spring如何注入静态变量

有些时候,我们需要将bean作为静态变量注入到类中,但是Spring本身不支持这么做,本文列举了两种变通的方法。

方法一

@Component
public class ConfigManager {
    private static ConfigMapper configMapper;
    @Autowired
    public void setConfigMapper(ConfigMapper _configMapper) {
        configMapper = _configMapper;
    }
    public static String getConfig(ITenantConfig tenantConfig) {
        ConfigVo configVo = configMapper.getConfigByKey(tenantConfig.getKey());
        if (configVo != null) {
            return configVo.getValue();
        }
        return tenantConfig.getValue();
    }
}

值得注意的是,ConfigMapper并没有被标记为@Component、@Service却同样能被注入,前提是ConfigMapper被注入的类自身要被标记为@Component、@Service

方法二

@Component
public class TestClass {
   private static AutowiredTypeComponent component;

   @Autowired
   private AutowiredTypeComponent autowiredComponent;

   @PostConstruct
   private void init() {
      component = this.autowiredComponent;
   }

   public static void testMethod() {
      component.callTestMethod();
   }
}

Reference

java - Can you use @Autowired with static fields? - Stack Overflow