如何使用WebApplicationInitializer配置@EnableConfigurationProperties,@ ConfigurationProperties?

时间:2015-04-09 07:04:59

标签: spring spring-mvc spring-boot spring-java-config

我想使用

阅读application.properties
@EnableConfigurationProperties and @ConfigurationProperties.

我可以使用以下代码执行此操作:

Application.java

@SpringBootApplication
@EnableConfigurationProperties(ApplicationConfiguration.class)
public class Application {

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


ApplicationConfiguration.java

@ConfigurationProperties(prefix = "server")
public class ApplicationConfiguration {

    private String port;

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }
}

TestController.java

@Controller
public class TestController {

    @Autowired
    ApplicationConfiguration applicationConfiguration;

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        if (applicationConfiguration != null) {
            return applicationConfiguration.getPort();
        }
        return "1";
    }
}

application.properties

server.port = 8085

现在我想用SpringBoot(Application.java)替换WebApplicationInitializer,以便我可以使用外部容器。这是我的代码:

CommonInitializer.java

public class CommonInitializer implements WebApplicationInitializer{
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
        annotationConfigWebApplicationContext.register(WebConfiguration.class);
        annotationConfigWebApplicationContext.setServletContext(servletContext);

        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));

        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
} 

WebConfiguration.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "hello")
@EnableAutoConfiguration
@EnableConfigurationProperties(ApplicationConfiguration.class)
public class WebConfiguration {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }
}

执行此操作后,我无法在application.proerties中获取端口(端口为null,applicationConfiguration不为null)。任何的想法?我错过了什么?

1 个答案:

答案 0 :(得分:4)

问题解决了。我缺少属性文件位置!!

@ConfigurationProperties(prefix = "server", locations = "classpath:application.properties")

看起来spring boot会自动为你做这件事。