Spring Boot 中的属性

Properties in Spring Boot

提问人:IRahi 提问时间:11/5/2023 更新时间:11/5/2023 访问量:29

问:

我在Spring Boot中使用属性bean。我总是得到的输出是 Spring Boot 无法从 application.properties 文件中调用该属性。我将所有配置文件属性文件放在一个单独的文件夹中,并在 appliction.properties 文件中激活它们,将路径粘贴到正确的位置 spring.config.name:

spring.config.name = properties
spring.profiles.active = optimistic,

我想如果我现在想访问 application.properties 文件,我必须使用我的 Bean 类定义一个新的 Properties 对象:

  1. 第一个是 FileInputstream: '''
package com.starter.tool.character.details;

import java.io.FileInputStream;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class Streams {
    
    private FileInputStream input;
    
    Streams(@Value("src/main/resources/application.properties" )String filePath)throws IOException{
        this.input = new FileInputStream(filePath);
    }
    
    public FileInputStream getStream() {
        return input;
    }
    
    

}

'''

  1. 第二个属性: '''

    package com.starter.tool.character.details;


import java.io.IOException;
import java.util.Properties;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class PropertyLoad {
    private final Properties props;

    
    PropertyLoad(Properties props){
        this.props = props;
        
    }

    @Bean
    @ConditionalOnBean(Streams.class)
    Properties defaultFormula(Streams input) {
        try {
            props.load(input.getStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        return props;
    }
}

'''

我知道Spring Boot有自己的Properties对象(startProperty),但是我用@Qualifier()注释解决了这个问题。请帮助我了解问题,为什么我无法访问 Properties 对象?

Java spring-boot 属性 配置文件 application.properties

评论


答: 暂无答案