@PropertySource & @ImportResource

@PropertySource:加载指定的配置文件。

/**
         * 将配置文件中配置的每一个属性的值,映射到这个组件中。
         * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定。
         * prefix = "person":即对应配置文件中哪个下面的所有属性一一映射。
 *
 *这个组件只有是容器中的组件时,才能使用容器提供的功能!@Component则是将其加入到容器中去。
 * @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值。
 *
**/


        @PropertySource(value={"classpath:person.properties"})//告诉SpringBoot来加载类路径(classpath)下的
                                                              // person.properties,并把他们绑定到这个person对象中
        @Component
        @ConfigurationProperties(prefix = "person")
        @Validated//开启数据校验注解!!!!
        public class Person {

            //@Value("")
            //@Email:指定该属性必须为邮箱格式
            //@Value("${person.last-name}")
            private String lastName;
            //@Value("#{11*2}")
            private Integer age;
            //@Value("true")
            private boolean boss;

 

 

 @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效。

  | Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别。想让Spring配置文件生效,则加进来@ImportResource标注在一个配置类上。

  

@ImportResource(locations = {"classpath:beans.xml"})
//在主类中加上这个,就能导入Spring的配置文件使其生效了

 

 

 

不来编写的配置文件了。下面是以前需要编写的配置文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="com.example.springboot01quick.Service.helloService"> </bean>

</beans>

 

SpringBoot推荐给容器中添加组件的方式:推荐使用全注解的方式

  | 1.配置类==(类似于)Spring配置文件

  | 2.使用@Bean给容器中添加组件

    

package com.example.springboot01quick.config;


import com.example.springboot01quick.Service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//指明当前类是一个配置类。就是来替代Spring配置文件的
public class MyAppConfig {

    //@Bean:将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名。
    @Bean//相当于xml配置文件中的bean标签
    public HelloService helloService(){
        System.out.println("配置类@Beangei容器添加组件了...");
        return new HelloService();
    }

}

 

posted @ 2020-07-28 11:33  初雨了然  阅读(16)  评论(0)    收藏  举报