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();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值