在Spring中,可以使用PropertyPlaceholderConfigurer或PropertySourcesPlaceholderConfigurer來加載外部配置文件。
PropertyPlaceholderConfigurer加載外部配置文件:<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties"/>
</bean>
其中,config.properties是外部配置文件的路徑。
PropertySourcesPlaceholderConfigurer加載外部配置文件:@Configuration
@PropertySource("classpath:config.properties")
public class AppConfig {
// ...
}
在這種方式下,需要在Spring的Java配置類上使用@PropertySource注解,并指定外部配置文件的路徑。
在兩種方式下,外部配置文件中的屬性可以通過@Value注解或Environment對象進行注入和訪問。
@Value("${property.key}")
private String propertyValue;
@Autowired
private Environment env;
public void someMethod() {
String propertyValue = env.getProperty("property.key");
}