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

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

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

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

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

常規(guī)操作:

注入類或者方法:

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

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

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

我們使用相同的方式進(jìn)行注入

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

我們?cè)陟o態(tài)方法使用的時(shí)候,會(huì)出現(xiàn)null;

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

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

  • (1)@PostConstruct方式實(shí)現(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方法注入實(shí)現(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實(shí)現(xiàn)靜態(tài)注入(類或者屬性)操作示例的詳細(xì)內(nèi)容,更多關(guān)于spring靜態(tài)注入類屬性的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論

微山县| 合作市| 惠安县| 富源县| 益阳市| 凌源市| 安义县| 新龙县| 合水县| 奉化市| 天峻县| 隆回县| 讷河市| 疏勒县| 和田县| 阳泉市| 永福县| 习水县| 木里| 时尚| 荔浦县| 龙门县| 色达县| 新绛县| 民勤县| 山东省| 桦甸市| 霍邱县| 阿勒泰市| 手游| 右玉县| 宽甸| 龙里县| 绥芬河市| 彩票| 微山县| 莒南县| 塘沽区| 华坪县| 股票| 淄博市|