How to add Properties to an Application Context

后端 未结 4 1803
感情败类
感情败类 2020-12-15 20:18

I have a Standalone Application, this application calculates a value (Property) and then starts a Spring Context. My question is how can I add that calculated property to th

4条回答
  •  一个人的身影
    2020-12-15 20:52

    In Spring 3.1 you can implement your own PropertySource, see: Spring 3.1 M1: Unified Property Management.

    First, create your own PropertySource implementation:

    private static class CustomPropertySource extends PropertySource {
    
        public CustomPropertySource() {super("custom");}
    
        @Override
        public String getProperty(String name) {
            if (name.equals("myCalculatedProperty")) {
                return magicFunction();  //you might cache it at will
            }
            return null;
        }
    }
    

    Now add this PropertySource before refreshing the application context:

    AbstractApplicationContext appContext =
        new ClassPathXmlApplicationContext(
            new String[] {"applicationContext.xml"}, false
        );
    appContext.getEnvironment().getPropertySources().addLast(
       new CustomPropertySource()
    );
    appContext.refresh();
    

    From now on you can reference your new property in Spring:

    
    
    
        
    
    

    Also works with annotations (remember to add ):

    @Value("${myCalculatedProperty}")
    private String magic;
    
    @PostConstruct
    public void init() {
        System.out.println("Magic: " + magic);
    }
    

提交回复
热议问题