gpt4 book ai didi

spring - 如何使用 WebApplicationInitializer 配置 @EnableConfigurationProperties、@ConfigurationProperties?

转载 作者:行者123 更新时间:2023-12-05 03:13:32 25 4
gpt4 key购买 nike

我想使用

读取 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

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

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 中获取端口(端口为空,applicationConfiguration 不为空)。任何想法?我错过了什么?

最佳答案

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

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

似乎 spring boot 会自动为您完成。

关于spring - 如何使用 WebApplicationInitializer 配置 @EnableConfigurationProperties、@ConfigurationProperties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com