Spring將類注入到IOC容器(方法及注意)
阿新 • • 發佈:2021-01-11
參考:https://www.cnblogs.com/ming-blogs/p/12011897.html
向Spring 容器中注入物件的幾種方法
1.使用@Bean 註解,用於注入第三方 jar 包到SpringIOC容器中。
2.使用@Import({Order.class, Member.class, MyImportBeanDefinitionRegistrar.class}) 註解,可以注入多個類,多個類之間使用 , 分割,主要用於注入第三方的 jar 包到SpirngIOC容器中。
3.在類檔案的開頭寫上以下中一個(具體哪一個自己看情況選擇)
(1)、@Component(“id”) :通用的
(2)、@Repository(“id”) :dao層註解
(3)、@Service(“id”) :service層註解
(4)、@Conroller(“id”) :控制器層註解
底層是使用@Component 註解實現。注意:使用@Component 需要開啟掃包範圍。
例如,在Student類前面加上@Component(“student”);並且匯入相應的包
import org.springframework.stereotype.Component;(id名字做為唯一識別符號)
4.在容器中配置掃描器:
(1)、在beans中新增xmlns:context=“http://www.springframework.org/schema/context”
(2)、新增標籤
<context:component-scan base-package=“包名”></context:component-scan>
原理:spring在啟動時會根據base-package在填寫的包中掃描所有類(包名可以填寫多個,中間用英文逗號隔開),將類中所有有註解的類全部加入到IOC容器中