在使用spring編程時,常常會遇到想根據bean的名稱來獲取相應的bean對象,這時候,就可以通過實現BeanFactoryAware來滿足需求,代碼很簡單:
@Service
public class BeanFactoryHelper implements BeanFactoryAware { private static BeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public static Object getBean(String beanName){
if(beanFactory == null){
throw new NullPointerException("BeanFactory is null!"); }
return beanFactory.getBean(beanName);
}
}
還有一種方式是實現ApplicationContextAware接口,代碼也很簡單:
@Service public class ApplicationContextHelper implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public static Object getBean(String beanName){ if(applicationContext == null){ throw new NullPointerException("ApplicationContext is null!"); } return applicationContext.getBean(beanName); } }
上面兩種方法,只有容器啟動的時候,才會把BeanFactory和ApplicationContext注入到自定義的helper類中,如果在本地junit測試的時候,如果需要根據bean的名稱獲取bean對象,則可以通過ClassPathXmlApplicationContext來獲取一個ApplicationContext,代碼如下:
@Test public void test() throws SQLException { //通過從classpath中加載spring-mybatis.xml實現bean的獲取 ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml"); IUserService userService = (IUserService) context.getBean("userService"); User user = new User(); user.setName("test"); user.setAge(20); userService.addUser(user); }