---
title: "获取spring的bean"
author: "liuna2011"
date: "2013-01-14T13:20:34Z"
tags: []
categories: ["编程语言"]
slug: "spring-bean"
draft: false
lastmod: "2013-01-14T13:20:34Z"
id: 1769354
url: "https://liuna2011.iteye.com/blog/1769354"
---

<span style="color:darkblue">**1.servlet中**</span>


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

```

<span style="color:darkblue">**2.普通java类中**</span>


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

```


```java

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;
    }
}


```

<span style="color:darkblue">**3.用命令行运行java程序**</span>

在main方法里2行代码就可以拿到service，然后直接调用其方法即可

```java
BeanFactory bf = new ClassPathXmlApplicationContext("spring-*.xml");
GameServiceImpl gameService = (GameServiceImpl) bf.getBean("gameService");
```


```java
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方法所在的类