Java后台代碼調用Spring的@Service Bean的方式


比如:在我的project中有一個類CompassIndexOperation,以:
@Service("CompassIndexOperation")

@Transactional

方式通知Spring創建一個實現類的實例;

Spring配置xml文件里設置了生成bean的文件文件夾,我的project實例為:

<context:component-scan base-package="com.ourfuture.compass.*"/>

這樣。project啟動時。會將制定文件夾下的以@Service等標記的類生成bean

在后台Java代碼中調用這一bean的方式例如以下:

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext

(ServletActionContext.getServletContext());

CompassIndexOperation compassIndexOperation = (CompassIndexOperation) context.

getBean("CompassIndexOperation");

這樣就獲得了Spring中的CompassIndexOperation Bean實例,當然這是我的project中的Bean。針對不同的project,要獲取不同的Bean實例,

僅僅需將上述的CompassIndexOperation 的位置改為相應的Bean的名字就可以。

當中須要導入的包有:

import org.springframework.context.ApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM