通常情况下我们在创建spring项目的时候在xml配置文件中都会配置这个标签,配置完这个标签后,spring就会去自动扫描base-package对应的路径或者该路径的子包下面的java文件,如果扫描到文件中带有@Service,@Component,@Repository,@Controller等这些注解的类,则把这些类注册为bean
注:在注解后加上例如@Component(value=”abc”)时,注册的这个类的bean的id就是adc.
在注解注入之前也必须在spring的配置文件中做如下配置,我们看下spring.xml文件的内容:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.sparta.trans" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
这个配置文件中必须声明xmlns:context 这个xml命名空间,在schemaLocation中需要指定schema:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
这个文件中beans根节点下只有一个context:component-scan节点,此节点有两个属性base-package属性告诉spring要扫描的包,use-default-filters=”false”表示不要使用默认的过滤器,此处的默认过滤器,会扫描包含@Service,@Component,@Repository,@Controller注解修饰的类,use-default-filters属性的默认值为true,这就意味着会扫描指定包下标有@Service,@Component,@Repository,@Controller的注解的全部类,并注册成bean。
所以如果仅仅是在配置文件中写<context:component-scan base-package="com.sparta.trans"/> Use-default-filter此时为true时,那么会对base-package包或者子包下所有的java类进行扫描,并把匹配的java类注册成bean。
所以这种情况下可以发现扫描的力度还是挺大的,但是如果你只想扫描指定包下面的Controller,那该怎么办?此时子标签<context:incluce-filter>就可以发挥作用了。如下所示
<context:component-scan base-package="com.sparta.trans" use-default-filters=”false”>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
@Service告诉spring容器,这是一个Service类,标识持久层Bean组件,默认情况会自动加载它到spring容器中。
@Autowried注解告诉spring,这个字段需要自动注入
@Scope指定此spring bean的scope是单例
@Repository注解指定此类是一个容器类,是DAO层类的实现。标识持久层Bean组件
@Componet:基本注解,标识一个受Spring管理的Bean组件
@Controller:标识表现层Bean组件
转载自:https://blog.csdn.net/qwe5810658/article/details/74343228
相关知识
Spring表达式和Spring注解
Spring
@Autowired(required=false)注入注意的问题
基于Spring Boot的宠物医院管理系统设计与实现
spring=画蛇添足
quartz 中JobExecutionContext的使用
记住!spring配置文件中的 configLocation' value= 记得带上,指定到mybatis的配置文件
在 Spring Boot 中使用 Logback 和 Log4j2 记录日志
如何优雅地记录操作日志?
二、spring mvc模拟用户增删改查以及登录和上传文件的相关流程
网址: spring中注解注入 context:component https://m.mcbbbk.com/newsview681235.html
上一篇: 可爱的宠物名 |
下一篇: 【宠物食具】 |