Spring 注入靜態變數 解決方案

來源:互聯網
上載者:User

先說下我現在使用的版本:Spring3.0 annotation寫的

今天寫項目遇到了一個問題:想通過jstl自訂函數來實現頁面上面的一部分內容。通過Spring注入後發現報如下錯誤:

@Resource annotation is not supported on static fields

上網搜尋發現,Spring註解注入不支援靜態變數注入,遂想辦法解決。

 

首先看到的方法是有一個 Java代碼   <bean id=”userService”     class=”bookstore.service.UserService”     init-method=”init” destroy-method=”destroy”>        …   </bean>   

 

這樣的方法,通過編寫一個方法init(),然後通過xml配置 init-method=”init” ,在init方法中從取值賦成靜態,但是我不想寫xml,畢竟項目裡主要用的都是annotation方式,於是發現如下兩個註解:

@PostConstruct 和 @PreDestroy

一個是在初始化之後調用,一個是在摧毀之前調用。這樣就可以使用的。

我在junit下做了測試,就不發項目代碼了,代碼如下: Java代碼   @Resource   private HibernateTemplate hibernateTemplate;      private static TalentsDaoImplTest td;      @PostConstruct   public void init() {     td = this;     td.hibernateTemplate = this.hibernateTemplate;   }      @Test   public void testStatic() {     Talents talents = td.hibernateTemplate.get(Talents.class, 1L);     System.out.println(talents.getAge());   }  

 

 

發這篇只是發現,可能是這個問題出現的或者是使用的人比較少,但是這個解決方案真的不太好找,我就總結下來,希望可以給大家提供協助。

還有就是我這樣是可以解決了,不知道大家是否還有更好的解決辦法,歡迎大家共同來分享。


原文地址:http://irfen.iteye.com/blog/1335016

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.