Discuss / Java / 交作业

交作业

Topic source

ypx0410

#1 Created at ... [Delete] [Delete and Lock User]

使用Spring的Resource注入app.properties文件,然后读取该配置文件。
app.properties

test=Hello World

ResourceService:

@Componentpublic class ResourceService {
    @Value("classpath:/app.properties")
    private Resource resource;   

    @Autowired    
    private Properties properties;   
 
    @PostConstruct    
    public void init() throws IOException
    {
        properties.load(resource.getInputStream());    
    }

    public Properties getProperties(){
        return properties;    
    }

AppConfig:

public class AppConfig {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        ResourceService resourceService = context.getBean(ResourceService.class);        
        Properties properties = resourceService.getProperties();        
        String test = properties.getProperty("test");        
        System.out.println(test);    
    }
}

  • 1

Reply