SpringBoot | 配置文件的注入

SpringBoot | 配置文件的注入

1. 使用@PropertySource

使用 @PropertySource 注解可以从外部加载指定的配置文件,将配置文件与 JavaBean 相绑定,使 JavaBean 读取配置文件中的值

在类路径下创建一个 people.properties 文件

people.last-name=张三三
people.age=100
people.birth=2019/2/3
people.boss=false
people.maps.password=lwh123
people.maps.address=xxx
people.lists=a,b,c,d,e
people.dog.name=dog
people.dog.age=19

在 Bean 在绑定该配置文件

@Component
@ConfigurationProperties(prefix = “people”) // 对应配置文件中的前缀
@PropertySource(value = {“classpath:people.properties”}) // 指定从类路径下的 people.properties 文件获取配置文件的值
public class People {

private String lastName;
private Integer age;
private Boolean boss;
private Date birth;

private Map<String, String> maps;
private List<String> lists;
private Dog dog;

// 省略 getter/setter 方法

// 省略 toString 方法

}

这里的 @ConfigurationProperties(prefix = ‘people’) 指定了配置文件中使用的前缀,对应配置文件中的 people.xxx 配置项,而 @PropertySource(value = {“classpath:xxx}”) 则指定了从类路径下获取配置文件的信息

2. 使用@ImportResourse

使用@ImportResourse 注解可以导入 Spring 的配置文件,让配置文件里面的配置生效

先准备一个 Spring 的配置文件 beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<bean id="helloService" class="edu.just.springboot.service.HelloService"></bean>

如果没有进行其他配置,那么该 Spring 的配置文件也是不会生效的,如果想让配置文件生效,需要在主程序类上加上 @ImportResource(locations = …) 注解

@ImportResource(locations = {“classpath:beans.xml”}) // 导入类路径下的 Spring 配置文件
@SpringBootApplication
public class Springboot02ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot02ConfigApplication.class, args);
}
}

但是在实际开发中不可能为每一个组件都单独配置一个 xxx.xml 文件,然后再使用注解的方式进行导入,这样过于麻烦

SpringBoot 中推荐使用配置类的方法给容器中添加组件

新建一个配置类 MyApplicationConfig

@Configuration
public class MyApplicationConfig {
@Bean
public HelloService helloService() {
System.out.println(“helloService组件”);
return new HelloService();
}
}

其中的 @Configuration 注解用来指名当前类是一个配置类,替代 Spring 的 xml 配置文件,@Bean 注解类似于之前 Spring 配置文件中的 标签。

这里我将 HelloService 方法的返回值添加到 Spring 的容器中,该组件的默认 id 就是方法的名字,即 helloService


作者:EclipseO2
来源:CSDN
原文:https://blog.csdn.net/babycan5/article/details/85961474
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值