为什么要配置spring**.xml或者applicationContext.xml --学习笔记

1.在使用spring框架的时候,我们在创建一些常用类之后,就会回来配置spring**.xml文件,在其中增加相应的bean,我们学视频或者根据网上搭建框架,一般都知道需要做这一步。但是很多人可能实际上还是很困惑这一步的真正目的到底是什么?

根据思考和查阅,这里增加bean是为了在项目启动的时候,spring框架会先去加载spring**.xml文件,根据其中写的配置的那些beans,它会相应的创建这些类的对象。

只有这样,在项目中其他位置调用的@Autowire处注入这个类的地方,在运行时候才会有实际的对象来提供操作。

其实进一步思考,

<context:component-scan base-package="com.XX">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.XXX"/>
</context:component-scan>

我们一定是能够在 applicationContext.xml 这个配置文件中 看见这样的一个配置项,我们点进component-scan看其中的内容描述时可以看见:

<xsd:element name="component-scan">
        <xsd:annotation>
            <xsd:documentation><![CDATA[
    Scans the classpath for annotated components that will be auto-registered as
    Spring beans. By default, the Spring-provided @Component, @Repository, @Service,
    @Controller, @RestController, @ControllerAdvice, and @Configuration stereotypes
    will be detected.
翻译如下:
扫描路径下的配置了组件标签的类,将其自动注册为spring的beans。

默认情况下,spring提供的
@Component, @Repository, @Service,
@Controller、
@RestController、@ControllerAdvice和@Configuration
构造型
将被检测到。

哦,这样就明白了,实际上这里就是beans标签的汇总写法,否则一个项目中那么多的controller,如果挨个的去写,岂不是得累死。

也正是有了这个配置项,像那些service、dao才能够让我们使用 @Autowire标签和@Resource标签来注入。嗯,感觉现在明白了spring**.xml的具体用途了。

 

2.在查看代码的时候,我们发现有些在spring**.xml里的bean中的一些属性上带有标签,那这些又是干嘛的呢?

1. @Value("${properties.name}")
   private String name;
2. @Value(
"#{25}") private Integer age;

其实这个标签就可以理解为赋值语句,

第1个 是用来注入外部配置文件对应的property的值。

第2个 是更像是提供默认值,网上查到完整的写法  @Value("#{Obj.property?Obj.property : 25}") 说是必须从对象中取值,或者直接赋值。

 

posted @ 2021-07-08 16:37  EtherealWind  阅读(194)  评论(0编辑  收藏  举报