在使用spring編程時(shí),常常會(huì)遇到想根據(jù)bean的名稱來獲取相應(yīng)的bean對(duì)象,這時(shí)候,就可以通過實(shí)現(xiàn)BeanFactoryAware來滿足需求,代碼很簡(jiǎn)單:
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); } } |
還有一種方式是實(shí)現(xiàn)ApplicationContextAware接口,代碼也很簡(jiǎn)單:
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); } } |
上面兩種方法,只有容器啟動(dòng)的時(shí)候,才會(huì)把 BeanFactory 和 ApplicationContext 注入到自定義的helper類中,如果在本地junit測(cè)試的時(shí)候,如果需要根據(jù)bean的名稱獲取bean對(duì)象,則可以通過ClassPathXmlApplicationContext來獲取一個(gè)ApplicationContext,代碼如下:
1
2
3
4
5
6
7
8
9
10
|
@Test public void test() throws SQLException { //通過從classpath中加載spring-mybatis.xml實(shí)現(xiàn)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); } |
總結(jié)
以上就是小編分享給大家的Java編程實(shí)現(xiàn)Aware接口自定義獲取bean的兩種方式的全部?jī)?nèi)容,希望對(duì)大家有所幫助。如果有什么問題,可以留言,小編會(huì)及時(shí)回復(fù)大家。感謝大家對(duì)本站的支持!
原文鏈接:http://www.cnblogs.com/handsomeye/p/6277510.html