Day11——@PropertySource和@ImportResource以及@Bean

一. @PropertySource

前面讲到配置文件获取值,使用了 @ConfigurationProperties注解。而这个注解默认是从全局配置文件(即application.properties或application.yml中)获取值的那么我们自己定义的properties、yml文件,怎么获取这些文件里面的值呢?答案是:使用@PropertySource

在resources文件夹下new一个person.properties,如下:
在这里插入图片描述

二. @ImportResource

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;
SpringBoot里面没有Spring的配置文件,我们自己写的配置文件也不能自动识别;
想让Spring配置文件加载进来,需将@ImportResource标注在一个配置类上

例子:

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot02Config2Application {

    public static void main(String[] args) {

        SpringApplication.run(SpringBoot02Config2Application.class, args);
    }

}

三. @Bean

SpringBoot不推荐使用xml文件配置,推荐使用全注解方式

配置类==Spring配置文件

/**
 * @Configuration:指明当前类是一个配置类,就是来替代之前spring的配置文件
 *
 * 在配置文件中用<bean></bean>添加组件的
 */
@Configuration
public class MyConfig {

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

}
发布了383 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40634846/article/details/105710545