SpringBoot 获取配置文件属性(全5种,附项目Demo)

一. 使用 @PropertySource + Environment

@PropertySource 指定配置文件位置, Environment 读取配置文件属性。

@Configuration
@PropertySource(value = {"classpath:test.properties"})
public class TestConfig {

    @Autowired
    private Environment env;

    public Map<String, Object> map=new HashMap<>();

    @Bean
    public Map<String, Object> test() {
        String testName = env.getProperty("test1.name");
        Integer testId = Integer.valueOf(env.getProperty("test1.id"));
        System.out.println("test1 -> | testName -> " + testName + " | test id -> " + testId);
        map.put("name", testName);
        map.put("id", testId);
        return map;
    }

}

二. 使用 @PropertySource + @Value

@PropertySource 指定配置文件位置,@Value 指定 `key对应的值。

@Configuration
@PropertySource(value = {"classpath:test2.properties"})
public class Test2Config {

    @Value("${test2.name}")
    private String testName;

    @Value("${test2.id}")
    private Integer testId;

    public Map<String, Object> map2=new HashMap<>();

    @Bean
    public Map<String, Object> test2() {

        System.out.println("test2 -> | testName -> " + testName + " | test id -> " + testId);
        map2.put("name", testName);
        map2.put("id", testId);
        return map2;
    }
}

三. 如果是默认的 yaml 文件属性,则可以直接使用 @Value

如果使用 yaml 文件可以不指定 properties,同时方式3会覆盖方式2

@Configuration
public class Test3Config {

    @Value("${test3.name}")
    private String testName;

    @Value("${test3.id}")
    private Integer testId;

    public Map<String, Object> map3=new HashMap<>();

    @Bean
    public Map<String, Object> test2() {

        System.out.println("test3 -> | testName -> " + testName + " | test id -> " + testId);
        map3.put("name", testName);
        map3.put("id", testId);
        return map3;
    }
}

四. getter、setter 方法注入及获取配置

@Component
@PropertySource(value = {"classpath:test4.properties"})
@ConfigurationProperties(prefix="test4")
public class Test4Config {

    private String name;

    private Integer id;

    public String getName() {
        return name;
    }

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

}
@Autowired
private Test4Config test4Config;

@GetMapping(value = "/test4_config")
public void Test4Config(){
    System.out.println("test4 -> | testName -> " + test4Config.getName() + " | test id -> " + test4Config.getId());
}

五. 直接读取配置文件

public class Test5Config {

    public static String name;
    public static int id;

    private static String property = "test5.properties";

    private static Test5Config myConfig;

    static {
        myConfig = loadConfig();
    }

    private static Test5Config loadConfig() {
        if (myConfig == null) {
            myConfig = new Test5Config();
            Properties properties;
            try {
                properties = PropertiesLoaderUtils.loadAllProperties(property);

                name = properties.getProperty("test5.name");
                id = Integer.valueOf(properties.getProperty("test5.id"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return myConfig;
    }

    public Test5Config getInstance() {
        return myConfig;
    }

}
@GetMapping(value = "/test5_config")
public void Test5ConfigX(){
    System.out.println("test5 -> | testName -> " + Test5Config.name + " | test id -> " + Test5Config.id);
}

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
是的,可以在Spring Boot中使用XML文件来获取JSON格式的数据源配置信息,并通过`lxml`库进行解析和获取。需要进行以下步骤: 1. 在`application.properties`或`application.yml`文件中添加以下配置项,指定JSON格式的数据源配置文件的路径: ``` spring.datasource.config-file=classpath:data-source.json ``` 这里假设JSON格式的数据源配置文件名为`data-source.json`,且放置在`classpath`目录下。 2. 在XML配置文件中添加以下配置项,使用`lxml`库来解析JSON格式的数据源配置文件,并将其映射到数据源配置类中: ```xml <bean id="dataSourceConfig" class="com.example.demo.DataSourceConfig"> <property name="type" value="${dataSource.type}"/> <property name="url" value="${dataSource.url}"/> <property name="username" value="${dataSource.username}"/> <property name="password" value="${dataSource.password}"/> <property name="driverClassName" value="${dataSource.driverClassName}"/> </bean> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="type" value="com.alibaba.druid.pool.DruidDataSource"/> <property name="url" value="#{dataSourceConfig.url}"/> <property name="username" value="#{dataSourceConfig.username}"/> <property name="password" value="#{dataSourceConfig.password}"/> <property name="driverClassName" value="#{dataSourceConfig.driverClassName}"/> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:application.properties</value> </list> </property> <property name="ignoreUnresolvablePlaceholders" value="true"/> </bean> ``` 这里假设数据源配置类的类名为`DataSourceConfig`,并且使用的是`DruidDataSource`数据源。需要注意的是,需要在XML配置文件中添加一个`PropertyPlaceholderConfigurer` bean,来替换`${}`的占位符。 3. 创建数据源配置类`DataSourceConfig`,并添加相应的属性和getter/setter方法: ```java public class DataSourceConfig { private String type; private String url; private String username; private String password; private String driverClassName; // getters and setters } ``` 这里需要注意的是,`type`属性对应的是数据源的类名,需要和`DataSource` bean的`class`属性一致。 这样就可以在Spring Boot中使用XML配置文件和`lxml`库来获取JSON格式的数据源配置信息,并链接数据源了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值