最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

spring實現(xiàn)靜態(tài)注入(類或者屬性)操作示例

 更新時間:2023年07月20日 10:21:17   作者:wotrd  
這篇文章主要為大家介紹了spring實現(xiàn)靜態(tài)注入(類或者屬性)操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

spring實現(xiàn)靜態(tài)注入類或者屬性

場景是:工具類一般都是靜態(tài)方法,靜態(tài)方法只能訪問靜態(tài)屬性。所以,我們需要靜態(tài)注入類或者屬性。

常規(guī)操作:

注入類或者方法:

@Autowired
private TestService testService;
@Resource
private TestService testService;
@Value("${key}")
private String key;

這樣,我們就把容器里的類和Enviroment里的值注進去了。

靜態(tài)注入操作:

我們使用相同的方式進行注入

@Autowired
private static TestService testService;
@Resource
private static TestService testService;
@Value("${key}")
private static String key;

我們在靜態(tài)方法使用的時候,會出現(xiàn)null;

發(fā)現(xiàn)注入不進去。

靜態(tài)注入失敗解決兩種方式

  • (1)@PostConstruct方式實現(xiàn)
@Component??
public?class?TestUtil?{
   @Autowired    
   private?static?TestService?testService;
   private?static?TestUtil?testUtils;
      
   @PostConstruct??????
   public?void?init()?{??????????
      testUtils?=this;??????????
      testUtils.testService?=this.testService;??????
   }??
}

@PostConstruct 注解的方法在加載類的構(gòu)造函數(shù)之后執(zhí)行,也就是在加載了構(gòu)造函數(shù)之后,執(zhí)行init方法;

(@PreDestroy 注解定義容器銷毀之前的所做的操作)這種方式和在xml中配置 init-method和 destory-method方法差不多,定義spring 容器在初始化bean 和容器銷毀之前的所做的操作;

  • (2)set方法注入實現(xiàn)
@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方法注入,這種使用比較多

以上就是spring實現(xiàn)靜態(tài)注入(類或者屬性)操作示例的詳細(xì)內(nèi)容,更多關(guān)于spring靜態(tài)注入類屬性的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

大连市| 庄河市| 绥棱县| 碌曲县| 宕昌县| 博兴县| 于田县| 平陆县| 余庆县| 米脂县| 搜索| 漳平市| 临漳县| 五寨县| 海宁市| 六安市| 绿春县| 黄陵县| 迁安市| 阜平县| 武威市| 渭源县| 仪陇县| 南靖县| 休宁县| 新河县| 喀喇| 南开区| 湾仔区| 康乐县| 井冈山市| 独山县| 禹州市| 津南区| 文登市| 河西区| 蒲江县| 卢龙县| 分宜县| 新丰县| 吐鲁番市|