服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解Spring中的@PropertySource注解使用

详解Spring中的@PropertySource注解使用

2021-11-24 12:00懵懂小虎 Java教程

这篇文章主要介绍了Spring的@PropertySource注解使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

@PropertySource注解是Spring用于加载配置文件,默认支持.properties.xml两种配置文件。@PropertySource属性如下:

  • name:默认为空,不指定Spring自动生成
  • value:配置文件
  • ignoreResourceNotFound:没有找到配置文件是否忽略,默认false,4.0版本加入
  • encoding:配置文件编码格式,默认UTF-8 4.3版本才加入
  • factory:配置文件解析工厂,默认:PropertySourceFactory.class 4.3版本才加入,如果是之前的版本就需要手动注入配置文件解析Bean

接下来就使用@PropertySource来加载.properties.xml配置文件。这里模拟连接MySQL数据库。
首先添加依赖:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.6.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.6.RELEASE</version>
</dependency>
 
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.26</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>

准备属性配置文件jdbc.properties

?
1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306
jdbc.userName=root
jdbc.password=xiaohu

创建属性实体类来加载配置文件JdbcProperties

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
@Repository
@PropertySource(value = "classpath:jdbc.properties")
public class JdbcProperties {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.userName}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;
}

创建JDBC配置类JdbcConfig

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component
public class JdbcConfig {
    @Bean
    public DataSource dataSource(JdbcProperties jdbcProperties){
        System.out.println("打印获取到的配置信息:"+jdbcProperties);
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(jdbcProperties.getDriver());
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setUsername(jdbcProperties.getUserName());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }
}

创建Spring配置类SpringConfiguration

?
1
2
3
4
@Configuration
public class SpringConfiguration {
 
}

创建测试类测试读取配置文件

?
1
2
3
4
5
6
7
public class PropertySourceTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("config");
        DataSource dataSource = context.getBean("dataSource",DataSource.class);
        System.out.println(dataSource);
    }
}

查看输出结果:

打印获取到的配置信息:JdbcProperties(driver=com.mysql.cj.jdbc.Driver, url=jdbc:mysql://127.0.0.1:3306, userName=root, password=xiaohu)
org.springframework.jdbc.datasource.DriverManagerDataSource@58695725

从结果可以看出,我们的properties中的配置已经成功读取到,并且DataSource也从Spring容器中获取到。上面介绍注解的属性时,factory是4.3版本才加入的,那么如果4.3版本之前要解析配置文件又应该怎么处理呢?,这个时候就需要手动将解析配置文件的Bean注入到Spring容器中了,用法很简单,在SpringConfiguration类中添加如下代码即可:

?
1
2
3
4
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
    return new PropertySourcesPlaceholderConfigurer();
}

具体测试结果,就自行测试了。上面例子介绍了properties的使用,下面我们将配置文件换成xml文件。配置如下:

?
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="jdbc.driver">com.mysql.cj.jdbc.Driver</entry>
    <entry key="jdbc.url">jdbc:mysql://127.0.0.1:3306/test</entry>
    <entry key="jdbc.userName">root</entry>
    <entry key="jdbc.password">xiaohu</entry>
</properties>

然后将JdbcProperties类上的注解的配置文件换成xml文件。

?
1
@PropertySource(value = "classpath:jdbc.properties")

其他不用调整,执行测试类,输出的结果一样。因为上面介绍到@PropertySource默认支持propertiesxml的配置文件。我们可以查看PropertySourceFactory的默认实现DefaultPropertySourceFactory源码

?
1
2
3
4
5
6
7
public class DefaultPropertySourceFactory implements PropertySourceFactory {
 
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
    }
}

然后进入ResourcePropertySource类,源码这里使用了一个三元运算符,如果name为空,就使用默认Spring默认生成的name

?
1
2
3
4
5
6
7
8
9
public ResourcePropertySource(String name, EncodedResource resource) throws IOException {
        super(name, PropertiesLoaderUtils.loadProperties(resource));
        this.resourceName = getNameForResource(resource.getResource());
    }
    
public ResourcePropertySource(EncodedResource resource) throws IOException {
        super(getNameForResource(resource.getResource()), PropertiesLoaderUtils.loadProperties(resource));
        this.resourceName = null;
    }

这里可以看到调用了PropertiesLoaderUtils.loadProperties方法,进入到源码

?
1
2
3
4
5
public static Properties loadProperties(EncodedResource resource) throws IOException {
    Properties props = new Properties();
    fillProperties(props, resource);
    return props;
}

会调用fillProperties的方法,一直跟到调用最低的fillProperties方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
            throws IOException {
    InputStream stream = null;
    Reader reader = null;
    try {
        String filename = resource.getResource().getFilename();
        if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
            stream = resource.getInputStream();
            persister.loadFromXml(props, stream);
        }
        else if (resource.requiresReader()) {
            reader = resource.getReader();
            persister.load(props, reader);
        }
        else {
            stream = resource.getInputStream();
            persister.load(props, stream);
        }
    }
    finally {
        if (stream != null) {
            stream.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
}

第一个if判断文件后缀是否是xml结尾,常量XML_FILE_EXTENSION如下:

?
1
private static final String XML_FILE_EXTENSION = ".xml";

除了支持propertiesxml的配置文件方式,也支持yml配置文件的方式,不过需要自定义解析工厂,下面来实现怎么解析yml配置文件。引入可以解析yml文件的第三方库

?
1
2
3
4
5
<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.28</version>
</dependency>

创建yml解析工厂YamlPropertySourceFactory实现PropertySourceFactory

?
1
2
3
4
5
6
7
8
9
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        factoryBean.setResources(resource.getResource());
        Properties properties = factoryBean.getObject();
        return name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties);
    }
}

然后将JdbcProperties类的@PropertySource换成如下写法:

?
1
@PropertySource(value = "classpath:jdbc.yml",factory = YamlPropertySourceFactory.class)

执行测试类,输出结果与上面结果一样

打印获取到的配置信息:JdbcProperties(driver=com.mysql.cj.jdbc.Driver, url=jdbc:mysql://127.0.0.1:3306, userName=root, password=xiaohu)
org.springframework.jdbc.datasource.DriverManagerDataSource@58695725

证明我们自定义的解析yml配置文件就成功了。

到此这篇关于Spring的@PropertySource注解使用的文章就介绍到这了,更多相关Spring的@PropertySource注解使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/tenghu/p/15159414.html

延伸 · 阅读

精彩推荐