使用property文件加载bean

本文介绍了如何在Spring中使用Property文件加载Bean。通过案例展示了如何定义property文件,然后利用PropertiesBeanDefinitionReader来读取配置,最后在GenericApplicationContext中手动刷新容器以应用配置。

 

xml模式下的Bean加载篇章中我们看到容器AbstractRefreshableApplicationContext在方法loadBeanDefinitions中加载我们的beanDefinition,在子类AbstractXmlApplicationContext继承该方法loadBeanDefinitions(DefaultListableBeanFactory) ,指定XmlBeanDefinitionReader进行加载。

	/**
	 * Load bean definitions into the given bean factory, typically through
	 * delegating to one or more bean definition readers.
	 * @param beanFactory the bean factory to load bean definitions into
	 * @throws BeansException if parsing of the bean definitions failed
	 * @throws IOException if loading of bean definition files failed
	 * @see org.springframework.beans.factory.support.PropertiesBeanDefinitionReader
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 */
	protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
			throws BeansException, IOException;

也就是说如果我们需要以property形式加载的话,只要指定PropertiesBeanDefinitionReader进行阅读就行了,该reader不详解,我们这里看一个案例就行了。

案例:

定义一个property文件,property_parse_demo.property:

people.(class)=com.jack.ascp.purchase.app.test.spring.parse.People
people.name=jpl
people.gender=man

 

public class People {
    private String name;

    private String gender;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

 

代码:

    public static void main(String[] args) {
        GenericApplicationContext context = new GenericApplicationContext();
        BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry)context.getBeanFactory();
        PropertiesBeanDefinitionReader propertiesBeanDefinitionReader = new PropertiesBeanDefinitionReader(beanDefinitionRegistry);
        // 设置ResourceLoader为GenericApplicationContext
        propertiesBeanDefinitionReader.setResourceLoader(context);
        propertiesBeanDefinitionReader.loadBeanDefinitions("property_parse_demo.property");
        // GenericApplicationContext的刷新不在构造函数,手动刷新
        context.refresh();
        People people = context.getBean(People.class);
        System.out.println(people.getGender());
        System.out.println(people.getName());
    }

}

我们需要在容器创建之后指定reader,但是AbstractRefreshableApplicationContext

容器的刷新是在构造函数之中完成,因此我们使用GenericApplicationContext (通用容器)进行测试,并且在指定reader之后手动刷新容器。

 

 

 

 

### 使用 PropertySource 加载外部文件配置示例 在 Spring Boot 中,`PropertySource` 是一种机制,用于将外部配置文件中的属性加载到 Spring 环境中。以下是一个完整的示例,展示如何通过 `PropertySource` 加载外部文件。 #### 1. 引入依赖 确保项目的 `pom.xml` 文件中包含以下依赖项以支持 Lombok 和 Spring Boot 的功能[^2]: ```xml <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> ``` #### 2. 创建外部属性文件 假设有一个名为 `external.properties` 的外部属性文件,其内容如下[^3]: ```properties app.name=ExternalApp app.version=1.0.0 ``` #### 3. 使用 `PropertySource` 注解加载外部文件 在 Spring Boot 应用程序中,可以通过 `@PropertySource` 注解来加载外部文件。例如: ```java import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; @SpringBootApplication @PropertySource("file:/path/to/external.properties") // 指定外部文件路径 public class ExternalConfigApplication { @Value("${app.name}") private String appName; @Value("${app.version}") private String appVersion; public static void main(String[] args) { new SpringApplicationBuilder(ExternalConfigApplication.class).run(args); } @Bean public ApplicationRunner runner() { return args -> { System.out.println("Application Name: " + appName); // 输出外部文件中的值 System.out.println("Application Version: " + appVersion); }; } } ``` #### 4. 动态指定路径 如果需要动态指定外部文件路径,可以使用 `loader.path` 或者通过环境变量实现[^4]。例如: ```java @PropertySource("file:${external.config.path}/external.properties") public class ExternalConfigApplication { ... } ``` 运行时可以通过命令行参数传递 `external.config.path` 的值: ```bash java -Dexternal.config.path=/path/to/config -jar app.jar ``` #### 5. 配置日志文件 如果需要加载自定义的日志配置文件,可以在 `application.yml` 中指定日志配置路径[^5]: ```yaml logging: config: classpath:logback-custom.xml ``` #### 注意事项 - 如果外部文件路径不存在或文件无法读取,Spring Boot 将抛出异常。 - 可以通过 `@PropertySources` 注解同时加载多个外部文件[^1]。 ### 示例输出 运行上述代码后,控制台将输出以下内容: ```plaintext Application Name: ExternalApp Application Version: 1.0.0 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值