获取spring的bean
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方法所在的类