Spring Boot - set value from an external properties file

可紊 提交于 2019-12-24 20:04:35

问题


I have an external location set on my application.properties as below

spring.config.location=file:${catalina.home}/conf/app.properties

app.properties has a property as timeOut=10000. There are many other properties as well.

I need to set this property on my session something like this:

 session.setMaxInactiveInterval(timeOut_Property);

How can this be achieved?

Adding Controller:

@Controller
public class StartController  {

@Value("${spring.config.location.defaultTimeout}")
private int defaultTimeout;

@RequestMapping("login.do")
public String login(HttpServletRequest request, HttpSession session, Model model) {     
    session.setMaxInactiveInterval(defaultTimeout);     
    return null;        
}

回答1:


Your Main Application class should look like this:

@SpringBootApplication
@PropertySource(name = "general-properties", value = { "classpath:path to your app.properties"})
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(NayapayApplication.class, args);
    }
}

And change your controller to:

@Controller
public class StartController  {

    @Value("${timeOut}")
    private int defaultTimeout;

    @RequestMapping("login.do")
    public String login(HttpServletRequest request, HttpSession session, Model model) {     
        session.setMaxInactiveInterval(defaultTimeout);     
        return null;        
    }
}



回答2:


You can annotate the variable with this property in the class as:

@Value("${timeOut}")
private String timeOut;

Use this variable to set session inactive interval as:

session.setMaxInactiveInterval(timeOut);


来源:https://stackoverflow.com/questions/44179065/spring-boot-set-value-from-an-external-properties-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!