Spring将类注入到IOC容器(方法及注意)

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

posted @ 2021-01-11 12:10  龙流笔记  阅读(2127)  评论(0编辑  收藏  举报