Spring基础篇:利用注解将外部Properties属性注入到Bean中的方法

例子

通过data.properties给类DataSource.class的属性注入相应的值。

D a t a S o u r c e . c l a s s DataSource.class DataSource.class

public class DataSource {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
}

d a t a . p r o p e r t i e s data.properties data.properties

driverClassName=com.mysql.cj.jdbc.Driver
url:jdbc:mysql://localhost:3306/Kaven?useUnicode=true&characterEncoding=UTF-8
dataUsername=root
password=root

文件组织位置 注意*

properties文件放在resources目录下。

通过注解的方式

1.在Bean上加入@Compoent注解

@Component
public class DataSource {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
}

使DataSource类被Spring容器管理,但目前缺少配置类,所以还不能将该类注册到容器中,现在我们来配置一下配置类

2.定义配置类

将配置类取名为:PropertiesAnnotationConfig,作为配置类,它有两个核心动作:

  1. 添加@Configuration注解,表示该类是Spring容器的配置类。
  2. 添加@ComponentScan注解,使用其一的方法:扫描某个包及其自包下,带有@Component或泛化注解的Bean注册到容器中。
@Configuration
@ComponentScan("juejin.properties")
public class PropertiesAnnotationConfig {
}

3.在配置类中使用@PropertySource注解 解析properties

@PropertySource("juejin/properties/data.properties")

其中juejin/properties/dataproperties对应的路径如下:

在这里插入图片描述

4.在Bean上使用@value注入属性

@Value("${driverClassName}")
private String driverClassName;
@Value("${url}")
private String url;
@Value("${dataUsername}")
private String username;
@Value("${password}")
private String password;

注解里面放上properties文件里面的键名就行

注意是使用这里先使用$符号。还有个#符号,将在后续介绍。

4.测试

这里我们通过AnnotationConfigApplicationContext类读取配置类,然后拿到Spring容器中的DataSourceBean,最后将其输出。

public class PropertiesAnnotationApplication {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(PropertiesAnnotationConfig.class);
        DataSource dataSource = ctx.getBean(DataSource.class);
        System.out.println(dataSource);
    }
}

5.结果

输出的结果,表明成功从外部文件中注入值到Bean中。

DataSource{driverClassName='com.mysql.cj.jdbc.Driver', url='jdbc:mysql://localhost:3306/Kaven?useUnicode=true&characterEncoding=UTF-8', username='root', password='root'}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值