Spring中记载属性文件

spring中加载属性文件有两种方式
1、配置类中的注解方式

@ComponentScan(basePackages = "spring")
@PropertySource(value = {"classpath:jdbc.properties"},ignoreResourceNotFound = true)
public class PojoConfig {

}

获取属性文件中的属性方法

 public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(PojoConfig.class);

        System.out.println(context.getEnvironment().getProperty("driver"));
    };

Spring中使用一个属性文件解析类处理属性文件(推荐)

@ComponentScan(basePackages = "spring")
@PropertySource(value = {"classpath:jdbc.properties"},ignoreResourceNotFound = true)
public class PojoConfig {
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }

}

调用方法
数据源Bean

@Component
public class DataSourceBean {
    @Value("${driver}")
    private String driver;
    @Value("${url}")
    private String url;
    @Value("${user}")
    private String user;
    @Value("${password}")
    private String password;

    @Bean("dataSource")
    public DataSource getDataSource(){
        Properties properties = new Properties();
        properties.setProperty("driver",driver);
        properties.setProperty("url",url);
        properties.setProperty("username",user);
        properties.setProperty("password",password);
        DataSource dataSource = null;
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }
}

使用XML加载属性文件

<context:property-placeholder ignore-resource-not-found="false" location="classpath:jdbc.properties"></context:property-placeholder>

当然,对于多个属性配置文件

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <array>
                <value>classpath:jdbc.properties</value>
                <value>calsspath:log4j.properties</value>
            </array>
        </property>
    </bean>









 

猜你喜欢

转载自blog.csdn.net/q1937915896/article/details/88219336