在使用spring編程時,常常會遇到想根據bean的名稱來獲取相應的bean對象,這時候,就可以通過實現BeanFactoryAware來滿足需求,代碼很簡單:
1
2
3
4
5
6
7
8
9
10
11
|
@Servicepublic 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接口,代碼也很簡單:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@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,代碼如下:
1
2
3
4
5
6
7
8
9
10
|
@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); } |
總結
以上就是小編分享給大家的Java編程實現Aware接口自定義獲取bean的兩種方式的全部內容,希望對大家有所幫助。如果有什么問題,可以留言,小編會及時回復大家。感謝大家對本站的支持!
原文鏈接:http://www.cnblogs.com/handsomeye/p/6277510.html