项目中new一个Spring管理的bean

来源:互联网 发布:php环境变量 编辑:程序博客网 时间:2024/05/16 09:34
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;/** * 获取应用上下文,获取Spring管理的bean * @author zzw * @date 2015-11-24 */@Componentpublic class SpringContext implements ApplicationContextAware {    protected static ApplicationContext context;        public static ApplicationContext getContext() {        return context;    }@Overridepublic void setApplicationContext(ApplicationContext applicationContext)throws BeansException {context = applicationContext;}}

注意“Component‘注解,将该类交于Spring管理。



/** * 获取Spring管理的bean * @author zzw * @date 2015-11-24 * */public class BeanFactory {/** * 获取Spring管理的Bean * @param beanName bean名称 * @return */ public static Object getBean(String beanName) {        return SpringContext.getContext().getBean(beanName);  }}



@Service("testService")public class TestService{}public class Test{    private TestService testService = BeanFactory.getBean("testService");}


0 0
原创粉丝点击