前言
在Spring中提供了非常多的方式注入實例,但是由于在初始化順序的不同,基于標注的注入方式,容易出現未被正確注入成功的情況。
本文將介紹一種在實際項目中基于動態的方式來提取Spring管理的Bean。 下面話不多說了,來一起看看詳細的介紹吧。
一、基于標注的方式注入實例
需要在Bean初始化之時,其依賴的對象必須初始化完畢。如果被注入的對象初始化晚于當前對象,則注入的對象將為null.
1.1 @Autowired
按照類型來加載Spring管理的Bean。默認情況下要求其Bean必須存在。 如果其Bean為null,則可以設置其required屬性為false。具體的詳情,可以參照源代碼:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interface Autowired {/** * Declares whether the annotated dependency is required. *Defaults to {@code true}.*/boolean required() default true;}如果需要基于命令來注入Bean,則需要使用@Qualifier來標注名稱,代碼示例如下:
@Autwired@Qualifier("beanName")private BeanType beanObj;應用范圍: 變量, setter方法和構造函數之上。
來源: Spring框架
1.2 @Inject
由javax.inject.Inject提供,基于類型進行自動裝配,如果需要按照名稱進行轉配,則需要配合使用@Named。這個使用方式和Spring框架提供的@Autowired非常類似。
應用范圍: 變量、setter方法,構造函數
來源: JSR330規范 javax擴展包
代碼示例:
@Inject@Named("beanName")private BeanType bean;1.3 @Resource
默認是按照名稱來裝配注入的,只有當找不到與名稱匹配的bean才會按照類型來裝配注入。其有JDK 1.6之后提供的。
應用范圍:可以應用到變量和setter方法之上
來源: JDK 1.6之后提供
代碼使用示例:
@Resource(name="mybeanName")private BeanType bean;
二、動態注入的方式
思路: 基于ApplicationContextAware來獲取ApplicationContext的引用,然后基于ApplicationContext進行對象的動態獲取。
實現代碼如下:
@Componentpublic 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實例了:
BeanType bean = SpringContextUtil.getBean("beanName")是不是非常容易使用呢?
總結
這里總結了在Spring中注入Bean的各種方式,各有優劣,大家可以選擇使用。
好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VeVb武林網的支持。
新聞熱點
疑難解答
圖片精選