spring實現靜態注入(類或者屬性)
阿新 • • 發佈:2019-08-14
spring實現靜態注入(類或者屬性)
場景是:工具類一般都是靜態方法,靜態方法只能訪問靜態屬性。所以,我們需要靜態注入類或者屬性。
常規操作:
注入類或者方法:
@Autowired
private TestService testService;
[@Resource](https://my.oschina.net/u/929718)
private TestService testService;
@Value("${key}")
private String key;
這樣,我們就把容器裡的類和Enviroment裡的值注進去了。
靜態注入操作:
我們使用相同的方式進行注入
@Autowired
private static TestService testService;
[@Resource](https://my.oschina.net/u/929718)
private static TestService testService;
@Value("${key}")
private static String key;
我們在靜態方法使用的時候,會出現null; 發現注入不進去。
解決辦法有兩種方式: (1)@PostConstruct方式實現
@Component public class TestUtil { @Autowired private static TestService testService; private static TestUtil testUtils; @PostConstruct public void init() { testUtils =this; testUtils.testService =this.testService; } }
@PostConstruct 註解的方法在載入類的建構函式之後執行,也就是在載入了建構函式之後,執行init方法;(@PreDestroy 註解定義容器銷燬之前的所做的操作)這種方式和在xml中配置 init-method和 destory-method方法差不多,定義spring 容器在初始化bean 和容器銷燬之前的所做的操作;
(2)set方法注入實現
@Component public class TestUtil { private static TestService testService; private static String key; @Value("{key}") public void setTestService(String key) { TestUtil.key = key; } @Autowired public void setTestService(TestService testService) { TestUtil.testService =this.testService; } }
ok,完事,使用set方法注入,這種使用比較多
有問題請留言!
個人部落格地址 https://blog.ailijie.to