參考: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容器中