Spring加载properties文件

注:本文的实现方式全部都是用javaconfig,无任何的xml.

spring提供了一个类:PropertySourcesPlaceholderConfigurer来加载properties,

先帖上实现代码:

@Configuration
@SuppressWarnings("UnusedDeclaration")
public class PropertySourcesConfig {
    private static final Resource[] DEV_PROPERTIES = new ClassPathResource[]{
            new ClassPathResource("app-dev.properties"),
    };
    
    @Profile("dev")
    @PropertySource(value = {"classpath:app-dev.properties"})
    @SuppressWarnings("UnusedDeclaration")
    public static class DevConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        pspc.setLocations(DEV_PROPERTIES);//可以加载多个
        return pspc;
    }
}
}

注解说明:

@Profile("dev")  :  如果当前的环境是dev, 那么就加载此配置 一般和 @ActiveProfiles(value = "dev")一起使用, 其他方式请自行google.

@PropertySource  :  只会将配置文件的内容加载到Environment对象中, 而不能进行javabean的属性进行占位符的替换,所以进程和PropertySourcesPlaceholderConfigurer一起使用.

使用PropertySourcesPlaceholderConfigurer的好处是:可以对javabean的属性进行占位符的替换如下:

public class User {
    @Value("${userName}")
    private String userName;
}

如果直接获取某个属性key对应的值那么可以使用Environment对象,如进行datasource配置

public class AppConfig {
    
    @Inject
    private Environment env;
    
    @Bean(name = "dataSource")
    @Profile({"dev"})
    public DataSource dataSource() {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("db.driverClassName"));
        dataSource.setUrl(env.getProperty("db.url"));
        dataSource.setUsername(env.getProperty("db.user"));
        dataSource.setPassword(env.getProperty("db.password"));
        dataSource.setValidationQuery("select 1");
        return dataSource;
    }
}





你可能感兴趣的:(Spring加载properties文件)