比如:在我的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;