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");

浙公网安备 33010602011771号