sping中@import
生活随笔
收集整理的這篇文章主要介紹了
sping中@import
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給容器中注冊組件:
-
包掃描 + 組件標注注解(@Controller/@Service/@Repository/@Component) 有局限性,針對自己寫的類可以加這些注解,但是對于導入的第三方包,如果沒加這些注解,則無法在spring中進行bean的管理
-
@Bean【導入第三方包里面的組件】
-
@Import【快速給容器中導入一個組件】
- @Import(要導入到容器的組件);容器中就會自動注冊這個組件,id默認是全類名
代碼:
測試代碼:
package common;import common.config.MainConfig; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class TestImport {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);private void printBeans(AnnotationConfigApplicationContext applicationContext) {String[] definitionNames = applicationContext.getBeanDefinitionNames();for (String name : definitionNames){System.out.println(name);}}@Testpublic void testImport(){printBeans(applicationContext);} }輸出:
二月 27, 2019 2:25:28 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@8807e25: startup date [Wed Feb 27 14:25:28 CST 2019]; root of context hierarchy org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory mainConfig testimport.Color peron- ImportSelector 接口,方法selectImports返回需要導入的全類名數組
測試的結果顯示如下:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory mainConfig testimport.Color testimport.Red testimport.Blue peron接口ImportSelector的方法selectImports返回的組件的全類名已經全部注入到組件
- ImportBeanDefinitionRegistrar.registerBeanDefinitions注冊組件 手動注冊bean
測試輸出:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.annotation.internalRequiredAnnotationProcessor org.springframework.context.annotation.internalCommonAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory mainConfig testimport.Color testimport.Red testimport.Blue peron rainbowimport注冊組件的方式比較重要,做個記錄
轉載于:https://my.oschina.net/wuyiyi/blog/3015510
總結
以上是生活随笔為你收集整理的sping中@import的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3分钟学会如何调度运营海量Redis系统
- 下一篇: vue中如何深度监听一个对象?