开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天,点击查看活动详情
例子
通过data.properties给类DataSource.class的属性注入相应的值。
public class DataSource {
private String driverClassName;
private String url;
private String username;
private String password;
}
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,作为配置类,它有两个核心动作:
- 添加
@Configuration注解,表示该类是Spring容器的配置类。 - 添加
@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'}