一直想总结一下spring获取bean的方式,我只记录三种,自以为三种应该就够我用了。
1.在spring的配置文件中配置自动扫描<context:component-scan base-package="*"></context:component-scan>,*代表你要扫描的包。在你需要由spring管理的类头上加上@Component 注解,这样在需要用到此bean的地方用
@Autowired
private TestService testService;
即可注入bean。
这种方式是我在项目中最常用也是感觉最方便的一种,这种方式在一般情况下都适用。
2.
ServletContext sc = request.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
UserService userService = (UserService) cxt.getBean("userService");
这是第二种方式,我用这种方式主要是解决一种第一种方式解决不了的情况。举个例子,就是在web项目的Filter中需要获取spring管理的bean时,第一种方式是不能实现的。因为在项目启动时,初始化filter的时候,spring还没来得及扫描bean。这时就可以用这个方式来获取bean了。
3.实现ApplicationContextAware接口
- public class SpringContextUtil implements ApplicationContextAware {
- // Spring应用上下文环境
- private static ApplicationContext applicationContext;
- /**
- * 实现ApplicationContextAware接口的回调方法。设置上下文环境
- *
- * @param applicationContext
- */
- public void setApplicationContext(ApplicationContext applicationContext) {
- SpringContextUtil.applicationContext = applicationContext;
- }
- /**
- * @return ApplicationContext
- */
- public static ApplicationContext getApplicationContext() {
- return applicationContext;
- }
- /**
- * 获取对象
- *
- * @param name
- * @return Object
- * @throws BeansException
- */
- public static Object getBean(String name) throws BeansException {
- return applicationContext.getBean(name);
- }
- }
这种情况可以用在项目中写一个获取bean的工具类,这种方式可以处理事先不确定要获取哪个bean的业务情况。