這期內容當中小編將會給大家帶來有關Spring中的bean怎么利用Aware接口獲取,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
在使用spring編程時,常常會遇到想根據bean的名稱來獲取相應的bean對象,這時候,就可以通過實現BeanFactoryAware來滿足需求,代碼很簡單:
@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接口,代碼也很簡單:
@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);
}上述就是小編為大家分享的Spring中的bean怎么利用Aware接口獲取了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。