spring 獲取對象方式


1 通過配置文件注入

1.配置文件里配置注入信息

2.class中加入注解的接口(set get、 構造函數等)

2.通過注解方式獲得

1. 在class中對方法加入注解信息 (類標示 :@Service 、@Repository  ;  注入標示:@Resource) 

3. 在spring環境中獲取對象(從web環境中獲取)

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
SystemUserDao systemUserDao  = (SystemUserDao)webApplicationContext.getBean("systemUserDao");

4. 怎樣在方法中使用getBean(從web環境中獲取)

當想在service方法中直接通過bean名稱獲取對象時,一種方法是加入request參數(這樣就能使用web環境中的spring環境了)。只是在service方法中有request參數明顯不是一種非常好的方法(不利於測試)。另外一種方法則加入一個SpringContent工具類。使用一個靜態變量存儲spring對象環境。在使用之前設置這個變量(web環境能夠加入filter、在測試環境也能夠對其進行社會自),詳細使用的時候則直接使用就可以。

工具類代碼:
package eway.flight.service;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Title: SpringContextUtil.java
 * @Package eway.flight.utils
 * @Description: TODO(加入描寫敘述)
 * @author A18ccms A18ccms_gmail_com
 * @date 2014-8-18 下午1:56:54
 * @version V1.0
 */
public class SpringContextUtil implements ApplicationContextAware {
	 private static ApplicationContext applicationContext;     //Spring應用上下文環境
	 
	 
	 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
	   SpringContextUtil.applicationContext = applicationContext;
	 }
	 
	 
	 public static ApplicationContext getApplicationContext() {
	   return applicationContext;
	 }
	 
	 
	 public static Object getBean(String name) throws BeansException {
	   return applicationContext.getBean(name);
	 }
	 
	 
	 public static Object getBean(String name, Class requiredType) throws BeansException {
	   return applicationContext.getBean(name, requiredType);
	 }
	 
	 
	 public static boolean containsBean(String name) {
	   return applicationContext.containsBean(name);
	 }
	 
	 
	 public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
	   return applicationContext.isSingleton(name);
	 }
	 
	 
	 public static Class getType(String name) throws NoSuchBeanDefinitionException {
	   return applicationContext.getType(name);
	 }
	 
	 
	 public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
	   return applicationContext.getAliases(name);
	 }
	}
web初始化時設置
	public void doFilter(ServletRequest request, ServletResponse response,
			// 設置靜態 spring 對象
			ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
			SpringContextUtil springContextUtil = new SpringContextUtil();
			springContextUtil.setApplicationContext(ctx);   
			
			
			chain.doFilter(request, response);
	}
業務代碼
	FlowCommItf command= (FlowCommItf)SpringContextUtil.getBean("flowComm_JSYSS");
		






免責聲明!

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



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