如何通过application.properties将bean作为属性公开

时间:2016-04-05 08:29:06

标签: java spring-boot

考虑以下bean:

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
    final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    resolver.setExposeContextBeansAsAttributes(true);
    return resolver;
}

如何通过application.properties重现setExposeContextBeansAsAttributes(true)

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
....

1 个答案:

答案 0 :(得分:1)

您需要创建Spring启动配置属性。

@ConfigurationProperties(prefix="spring.mvc.view")
public class SpringMvcViewProperties {

    private String prefix;

    private String suffix;

    private boolean exposeContext;

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public String getSuffix() {
        return suffix;
    }

    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }

    public boolean isExposeContext() {
        return exposeContext;
    }

    public void setExposeContext(boolean exposeContext) {
        this.exposeContext = exposeContext;
    }
}

然后使用该配置属性,如

@Bean
public InternalResourceViewResolver getInternalResourceViewResolver(SpringMvcViewProperties viewProps) {
    final InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix(viewProps.getPrefix());
    resolver.setSuffix(viewProps.getSuffix());
    resolver.setExposeContextBeansAsAttributes(viewProps.isExposeContext());
    return resolver;
}


// application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
spring.mvn.view.exposeContext=true