@Component@ComponentScan@Configuration
Posted 一菜一汤
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@Component@ComponentScan@Configuration相关的知识,希望对你有一定的参考价值。
1、@ComponentScan
这个是Spring的原生注解,主要用来指明哪些路径下的包要交给spring管理,注册到ioc容器中
在配置文件就相当于:
context:componet-scan
属性
<context:componet-scan base-package="com.sff.app" use-default-filters="true">
<!--不扫描@Controller注解的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:componet-scan>
我们一般可以这样使用:
@Configuration
@ComponentScan(value = "com.qch.test",
includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)},
useDefaultFilters = false)
public class AppConfig {
/*给容器中注册一个bean,类型是方法返回值,id就是方法名称*/
@Bean
public Person person() {
return new Person("Kate", 12);
}
}
表示像Spring的ico容器中注入一个配置类
因为Springboot中的@SpringBootApplication注解已经封装了这个注解,所以我们一般很少去使用这个注解来指定我们配置文件所在的路径
换句话说,只要我们按照SpirngBoot的规范,在主启动类下创建包就不需要额外的指定那个包名
2、@Configuration
该注解表示注册一个配置类到ioc容器中,我们还可以使用@Bean注解自定义像ioc中注入的组件
其中@Configuration就相当于我们告诉Springboot这是一个配置文件
使用 <bean></bean
标签来注册自定义组件 ===@Bean
<property></property>
表示相关属性
]
)[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fZv97XKQ-1620217630429)(]
)
Springboot2中我们还可以通过@Configuration注解的属性来指定是否每一次都从ioc容器中获取注册的组件还是每一次都创建一个新的
- ture 使用代理的示例,从ioc容器中获取,是一个单例
- false 每一次都创建一个新的对象
3、@Component
这个注解表示将向Spring容器中注册组件,这是Spring原生的注解
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jQd36TMo-1620217555927)(]
)
比如上面我们使用的@Configuration也封装了这个注解
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KKyC0sC0-1620217570012)(]
)
还有我们的@controller@service中也封装了这个注解
以上是关于@Component@ComponentScan@Configuration的主要内容,如果未能解决你的问题,请参考以下文章