---
title: "如何静态调用Spring容器的bean"
author: "labreeze"
date: "2017-03-12T19:58:26Z"
tags: []
categories: ["企业架构"]
slug: "spring-bean"
draft: false
lastmod: "2017-03-12T19:59:23Z"
id: 2361680
url: "https://labreeze.iteye.com/blog/2361680"
---

**背景：**

      最近工作中发现有个用法很有意思，如下代码：静态方法中引用Spring bean disconf的对象，这样就不用在B bean的用到disconf的地方声明然后注入这个bean了。相当于引入了第三个bean来实现解耦，这样用起来就很方便，直接调用静态方法即可。

      

    **代码：**

    

```
class A {
    private static DisconfService disconf;

    public static String getXProperty() {
        return disconf.xMethod();
    }
}

Class B {
    public void method() {
        A.getXProperty();
    }
}
```

    如何保证disconf 这个bean不为空呢？

 

    **技术实现：**

      **1.  xml配置**

    

```
class A {
    private static DisconfService disconf;

    public static String getXProperty() {
        return disconf.xMethod();
    }

    // 增加set方法
    public void setDisconf(DisconfService disconf) {
        A.disconf = disconf;
    }
}
```

 

```
<bean id="xx" class="A" >
   <p:disconf ref=disconf />
</bean>
```

 

     **2. A实现InitianBean**

     

```
class A implements InitialBean{

    @AutoWired
    private DisconfService disconfBean;

    private static DisconfService disconf;

    public void afterPropertiesSet() {
        A.disconf=disconfBean;
    }

    public static String getXProperty() {
        return disconf.xMethod();
    }
}
```