简体   繁体   中英

How to use one property into another property in Java with Spring?

I am using Spring MVC 4.0.2 for my web development. I am trying to declare my property (app.properties) file as given below.

login.view=login
login.url=/${login.view}

Now if I tries to access login.url like this,

@RequestMapping(value = "${login.url}", method = RequestMethod.GET)
public String login(ModelMap model)
{ 
      return "login";
}

It is working fine.

But when I tries to access same property like this,

String s = (String)PropertiesLoaderUtils.loadProperties(new ClassPathResource("app.properties")).getProperty("login.url");

I am getting output : ${login.url} , which should be /login . I am not getting why it happens. Any idea?

Sotirios's answer is correct as to why it is happening. Instead of loading through PropertiesLoaderUtils you can inject using @Value...

into a constructor:

public MyClass(@Value("${login.url}") String loginUrl) {...}

or a field:

@Value("${login.url}")
private String loginUrl;

or a setter:

@Value("${login.url}")
public void setLoginUrl(String loginUrl) {
  this.loginUrl = loginUrl;
}

This

String s = (String)PropertiesLoaderUtils.loadProperties(new ClassPathResource("app.properties")).getProperty("login.url");

doesn't apply any property resolution while the RequestMappingHandlerMapping that processes @RequestMapping annotations does.

finally I got answer,

public class PropertiesUtil extends PropertyPlaceholderConfigurer
{
    private static Map<String, Object>  propertiesMap;

    @SuppressWarnings({ "deprecation", "rawtypes" })
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException
    {
        super.processProperties(beanFactory, props);
        propertiesMap = new HashMap<String, Object>();
        for (Object key : props.keySet())
        {
            String keyStr = key.toString();
            propertiesMap.put(keyStr, parseStringValue(props.getProperty(keyStr), props, new HashSet()));
        }
    }

    public static String getProperty(String name)
    {
        return (String) propertiesMap.get(name);
    }
}

and Then

String s = PropertyUtil.getProperty("login.url");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM