ITeye博客

获取spring的bean

liuna2011 · 2013-01-14 13:20 · java · 编程语言 · Markdown

1.servlet中


ServletContext servletContext = this.getServletConfig().getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
DownloadService downloadService = (DownloadService) applicationContext.getBean("downloadService");


2.普通java类中

    
ApplicationContext context = SpringContext.getContext();
SymUserService ss = (SymUserService) context.getBean("symUserService");


import org.springframework.context.ApplicationContext;

public class SpringContext {
    public static ApplicationContext context ;

    public static ApplicationContext getContext() {
        return context;
    }

    public static void setContext(ApplicationContext context) {
        SpringContext.context = context;
    }
}


3.用命令行运行java程序

在main方法里2行代码就可以拿到service,然后直接调用其方法即可

BeanFactory bf = new ClassPathXmlApplicationContext("spring-*.xml");
GameServiceImpl gameService = (GameServiceImpl) bf.getBean("gameService");
F:\gamespider\web\WEB-INF\classes>java -classpath F:\gamespider\web\WEB-INF\classes -Djava.ext.dirs=F:\gamespider\web\WEB-INF\lib Test

Test是main方法所在的类

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。