how to read properties file in spring project?

后端 未结 5 1372
梦谈多话
梦谈多话 2020-12-06 01:28

Before post this Question, I google to get Properties from Spring project(Its NOT web-based project). I am confused as every one are talking about application-context.xml an

5条回答
  •  悲哀的现实
    2020-12-06 01:40

    You can create an XML based application context like:

    ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
    

    if the xml file is located on your class path. Alternatively, you can use a file on the file system:

    ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/appContext.xml");
    

    More information is available in the Spring reference docs. You should also register a shutdown hook to ensure graceful shutdown:

     ctx.registerShutdownHook();
    

    Next, you can use the PropertyPlaceHolderConfigurer to extract the properties from a '.properties' file and inject them into your beans:

    
        
    
    
    
        
        
        
        
    
    

    Lastly, if you prefer annotation based config, you can use the @Value annotation to inject properties into you beans:

    @Component
    public class SomeBean {
    
        @Value("${jdbc.url}") 
        private String jdbcUrl;
    }
    

提交回复
热议问题