[bs-83] Rename "container" -> "server"

* Also extracted ManagementServerProperties into a separate
bean
* TraceRepository was still causing problems during startup,
fixed that
* Allow management endpoints to be switched off with port=0

[Fixes #49046013]
This commit is contained in:
Dave Syer 2013-05-01 08:36:33 +01:00
parent ec0e9b17ad
commit ce2a2beab4
20 changed files with 303 additions and 110 deletions

View File

@ -1,8 +1,8 @@
logging.file: /tmp/logs/app.log logging.file: /tmp/logs/app.log
container.port: 8080 management.port: 8080
container.management_port: 8080 management.allow_shutdown: true
container.allow_shutdown: true server.port: 8080
container.tomcat.basedir: target/tomcat server.tomcat.basedir: target/tomcat
container.tomcat.access_log_pattern: %h %t "%r" %s %b server.tomcat.access_log_pattern: %h %t "%r" %s %b
security.require_ssl: false security.require_ssl: false
service.name: Phil service.name: Phil

View File

@ -0,0 +1,120 @@
package org.springframework.bootstrap.sample.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.bootstrap.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.crypto.codec.Base64;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import static org.junit.Assert.assertEquals;
/**
* Integration tests for switching off management endpoints.
*
* @author Dave Syer
*
*/
public class NoVarzContextServiceBootstrapApplicationTests {
private static ConfigurableApplicationContext context;
private static int managementPort = 0;
@BeforeClass
public static void start() throws Exception {
final String[] args = new String[] { "--management.port=" + managementPort };
Future<ConfigurableApplicationContext> future = Executors
.newSingleThreadExecutor().submit(
new Callable<ConfigurableApplicationContext>() {
@Override
public ConfigurableApplicationContext call() throws Exception {
return (ConfigurableApplicationContext) SpringApplication
.run(ServiceBootstrapApplication.class, args);
}
});
context = future.get(10, TimeUnit.SECONDS);
}
@AfterClass
public static void stop() {
if (context != null) {
context.close();
}
}
@Test
public void testHome() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = getRestTemplate("user", "password").getForEntity(
"http://localhost:8080", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertEquals("Hello Phil", body.get("message"));
}
@Test(expected = ResourceAccessException.class)
public void testVarzNotAvailable() throws Exception {
testHome(); // makes sure some requests have been made
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = getRestTemplate("user", "password").getForEntity(
"http://localhost:" + managementPort + "/varz", Map.class);
assertEquals(HttpStatus.NOT_FOUND, entity.getStatusCode());
}
private RestTemplate getRestTemplate(final String username, final String password) {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
if (username != null) {
interceptors.add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add(
"Authorization",
"Basic "
+ new String(Base64
.encode((username + ":" + password)
.getBytes())));
return execution.execute(request, body);
}
});
}
RestTemplate restTemplate = new RestTemplate(
new InterceptingClientHttpRequestFactory(
new SimpleClientHttpRequestFactory(), interceptors));
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return restTemplate;
}
}

View File

@ -44,8 +44,8 @@ public class VarzContextServiceBootstrapApplicationTests {
@BeforeClass @BeforeClass
public static void start() throws Exception { public static void start() throws Exception {
final String[] args = new String[] { "--container.port=" + port, final String[] args = new String[] { "--server.port=" + port,
"--container.management_port=" + managementPort }; "--management.port=" + managementPort };
Future<ConfigurableApplicationContext> future = Executors Future<ConfigurableApplicationContext> future = Executors
.newSingleThreadExecutor().submit( .newSingleThreadExecutor().submit(
new Callable<ConfigurableApplicationContext>() { new Callable<ConfigurableApplicationContext>() {

View File

@ -0,0 +1,4 @@
@Configuration
@Import(org.springframework.bootstrap.sample.service.ServiceBootstrapApplication)
class Start {
}

View File

@ -37,7 +37,7 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration @Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnMissingBean({ HealthzEndpoint.class }) @ConditionalOnMissingBean({ HealthzEndpoint.class })
public class HealthzAutoConfiguration { public class HealthzConfiguration {
@Autowired(required = false) @Autowired(required = false)
private HealthIndicator<? extends Object> healthIndicator = new VanillaHealthIndicator(); private HealthIndicator<? extends Object> healthIndicator = new VanillaHealthIndicator();

View File

@ -20,7 +20,8 @@ import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.bootstrap.context.annotation.ConditionalOnExpression; import org.springframework.bootstrap.context.annotation.ConditionalOnExpression;
import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContext; import org.springframework.bootstrap.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.bootstrap.service.properties.ManagementServerProperties;
import org.springframework.bootstrap.service.properties.ServerProperties;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
@ -34,19 +35,23 @@ import org.springframework.context.event.ContextRefreshedEvent;
* *
*/ */
@Configuration @Configuration
public class ManagementAutoConfiguration implements ApplicationContextAware, @ConditionalOnExpression("${management.port:8080}>0")
DisposableBean, ApplicationListener<ContextRefreshedEvent> { public class ManagementConfiguration implements ApplicationContextAware, DisposableBean,
ApplicationListener<ContextRefreshedEvent> {
private ApplicationContext parent; private ApplicationContext parent;
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;
@Autowired @Autowired
private ContainerProperties configuration = new ContainerProperties(); private ServerProperties configuration = new ServerProperties();
@ConditionalOnExpression("${container.port:8080} == ${container.management_port:8080}") @Autowired
private ManagementServerProperties management = new ManagementServerProperties();
@ConditionalOnExpression("${server.port:8080} == ${management.port:8080}")
@Configuration @Configuration
@Import({ VarzAutoConfiguration.class, HealthzAutoConfiguration.class, @Import({ VarzConfiguration.class, HealthzConfiguration.class,
ShutdownAutoConfiguration.class, TraceAutoConfiguration.class }) ShutdownConfiguration.class, TraceConfiguration.class })
public static class ManagementEndpointsConfiguration { public static class ManagementEndpointsConfiguration {
} }
@ -68,12 +73,12 @@ public class ManagementAutoConfiguration implements ApplicationContextAware,
if (event.getSource() != this.parent) { if (event.getSource() != this.parent) {
return; return;
} }
if (this.configuration.getPort() != this.configuration.getManagementPort()) { if (this.configuration.getPort() != this.management.getPort()) {
AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext(); AnnotationConfigEmbeddedWebApplicationContext context = new AnnotationConfigEmbeddedWebApplicationContext();
context.setParent(this.parent); context.setParent(this.parent);
context.register(ManagementContainerConfiguration.class, context.register(ManagementServerConfiguration.class,
VarzAutoConfiguration.class, HealthzAutoConfiguration.class, VarzConfiguration.class, HealthzConfiguration.class,
ShutdownAutoConfiguration.class, TraceAutoConfiguration.class); ShutdownConfiguration.class, TraceConfiguration.class);
context.refresh(); context.refresh();
this.context = context; this.context = context;
} }

View File

@ -30,7 +30,7 @@ import org.springframework.bootstrap.context.embedded.ErrorPage;
import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainerFactory; import org.springframework.bootstrap.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.bootstrap.service.error.ErrorEndpoint; import org.springframework.bootstrap.service.error.ErrorEndpoint;
import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.bootstrap.service.properties.ManagementServerProperties;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -45,10 +45,10 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc;
*/ */
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
public class ManagementContainerConfiguration implements BeanPostProcessor { public class ManagementServerConfiguration implements BeanPostProcessor {
@Autowired @Autowired
private ContainerProperties configuration = new ContainerProperties(); private ManagementServerProperties configuration = new ManagementServerProperties();
private boolean initialized = false; private boolean initialized = false;
@ -103,7 +103,7 @@ public class ManagementContainerConfiguration implements BeanPostProcessor {
&& !this.initialized) { && !this.initialized) {
AbstractEmbeddedServletContainerFactory factory = (AbstractEmbeddedServletContainerFactory) bean; AbstractEmbeddedServletContainerFactory factory = (AbstractEmbeddedServletContainerFactory) bean;
factory.setPort(this.configuration.getManagementPort()); factory.setPort(this.configuration.getPort());
factory.setContextPath(this.configuration.getContextPath()); factory.setContextPath(this.configuration.getContextPath());
factory.setErrorPages(Collections factory.setErrorPages(Collections

View File

@ -33,7 +33,7 @@ import org.springframework.context.annotation.Configuration;
* *
*/ */
@Configuration @Configuration
public class MetricAutoConfiguration { public class MetricConfiguration {
@Bean @Bean
@ConditionalOnMissingBean({ CounterService.class }) @ConditionalOnMissingBean({ CounterService.class })

View File

@ -50,7 +50,7 @@ import org.springframework.web.util.UrlPathHelper;
// FIXME: make this conditional // FIXME: make this conditional
// @ConditionalOnBean({ CounterService.class, GaugeService.class }) // @ConditionalOnBean({ CounterService.class, GaugeService.class })
@ConditionalOnClass({ Servlet.class }) @ConditionalOnClass({ Servlet.class })
public class MetricFilterAutoConfiguration { public class MetricFilterConfiguration {
@Autowired(required = false) @Autowired(required = false)
private CounterService counterService; private CounterService counterService;
@ -84,24 +84,28 @@ public class MetricFilterAutoConfiguration {
DateTime t0 = new DateTime(); DateTime t0 = new DateTime();
try { try {
chain.doFilter(request, response); chain.doFilter(request, response);
status = servletResponse.getStatus();
} finally { } finally {
try {
status = servletResponse.getStatus();
} catch (Exception e) {
// ignore
}
set("response", suffix, new Duration(t0, new DateTime()).getMillis()); set("response", suffix, new Duration(t0, new DateTime()).getMillis());
increment("status." + status, suffix); increment("status." + status, suffix);
} }
} }
private void increment(String prefix, String suffix) { private void increment(String prefix, String suffix) {
if (MetricFilterAutoConfiguration.this.counterService != null) { if (MetricFilterConfiguration.this.counterService != null) {
String key = getKey(prefix + suffix); String key = getKey(prefix + suffix);
MetricFilterAutoConfiguration.this.counterService.increment(key); MetricFilterConfiguration.this.counterService.increment(key);
} }
} }
private void set(String prefix, String suffix, double value) { private void set(String prefix, String suffix, double value) {
if (MetricFilterAutoConfiguration.this.gaugeService != null) { if (MetricFilterConfiguration.this.gaugeService != null) {
String key = getKey(prefix + suffix); String key = getKey(prefix + suffix);
MetricFilterAutoConfiguration.this.gaugeService.set(key, value); MetricFilterConfiguration.this.gaugeService.set(key, value);
} }
} }

View File

@ -42,7 +42,7 @@ import org.springframework.stereotype.Component;
@ConditionalOnMissingBean({ WebSecurityConfiguration.class }) @ConditionalOnMissingBean({ WebSecurityConfiguration.class })
@EnableWebSecurity @EnableWebSecurity
@EnableConfigurationProperties(SecurityProperties.class) @EnableConfigurationProperties(SecurityProperties.class)
public class SecurityAutoConfiguration { public class SecurityConfiguration {
@Component @Component
public static class WebSecurityAdapter extends WebSecurityConfigurerAdapter { public static class WebSecurityAdapter extends WebSecurityConfigurerAdapter {

View File

@ -33,8 +33,8 @@ import org.springframework.bootstrap.context.embedded.EmbeddedServletContainerFa
import org.springframework.bootstrap.context.embedded.ErrorPage; import org.springframework.bootstrap.context.embedded.ErrorPage;
import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.bootstrap.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.bootstrap.service.error.ErrorEndpoint; import org.springframework.bootstrap.service.error.ErrorEndpoint;
import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.bootstrap.service.properties.ServerProperties;
import org.springframework.bootstrap.service.properties.ContainerProperties.Tomcat; import org.springframework.bootstrap.service.properties.ServerProperties.Tomcat;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -45,12 +45,12 @@ import org.springframework.util.StringUtils;
* *
* @author Dave Syer * @author Dave Syer
*/ */
// Slight hack here (BeanPostProcessor), to force the container properties to be bound in // Slight hack here (BeanPostProcessor), to force the server properties to be bound in
// the right order // the right order
@Configuration @Configuration
@ConditionalOnClass({ Servlet.class }) @ConditionalOnClass({ Servlet.class })
@Order(Integer.MIN_VALUE) @Order(Integer.MIN_VALUE)
public class ContainerConfiguration implements BeanPostProcessor, BeanFactoryAware { public class ServerConfiguration implements BeanPostProcessor, BeanFactoryAware {
private BeanFactory beanFactory; private BeanFactory beanFactory;
@ -89,8 +89,8 @@ public class ContainerConfiguration implements BeanPostProcessor, BeanFactoryAwa
&& !this.initialized) { && !this.initialized) {
// Cannot use @Autowired because the injection happens too early // Cannot use @Autowired because the injection happens too early
ContainerProperties configuration = this.beanFactory ServerProperties configuration = this.beanFactory
.getBean(ContainerProperties.class); .getBean(ServerProperties.class);
AbstractEmbeddedServletContainerFactory factory = (AbstractEmbeddedServletContainerFactory) bean; AbstractEmbeddedServletContainerFactory factory = (AbstractEmbeddedServletContainerFactory) bean;
factory.setPort(configuration.getPort()); factory.setPort(configuration.getPort());
@ -114,7 +114,7 @@ public class ContainerConfiguration implements BeanPostProcessor, BeanFactoryAwa
} }
private void configureTomcat(TomcatEmbeddedServletContainerFactory tomcatFactory, private void configureTomcat(TomcatEmbeddedServletContainerFactory tomcatFactory,
ContainerProperties configuration) { ServerProperties configuration) {
Tomcat tomcat = configuration.getTomcat(); Tomcat tomcat = configuration.getTomcat();
if (tomcat.getBasedir() != null) { if (tomcat.getBasedir() != null) {

View File

@ -20,7 +20,8 @@ import java.util.List;
import org.springframework.bootstrap.context.annotation.EnableAutoConfiguration; import org.springframework.bootstrap.context.annotation.EnableAutoConfiguration;
import org.springframework.bootstrap.service.annotation.EnableConfigurationProperties; import org.springframework.bootstrap.service.annotation.EnableConfigurationProperties;
import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.bootstrap.service.properties.ManagementServerProperties;
import org.springframework.bootstrap.service.properties.ServerProperties;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter;
@ -36,9 +37,9 @@ import com.fasterxml.jackson.datatype.joda.JodaModule;
* @author Dave Syer * @author Dave Syer
*/ */
@Configuration @Configuration
@Import({ ManagementAutoConfiguration.class, MetricAutoConfiguration.class, @Import({ ManagementConfiguration.class, MetricConfiguration.class,
ContainerConfiguration.class, SecurityAutoConfiguration.class, ServerConfiguration.class, SecurityConfiguration.class,
MetricFilterAutoConfiguration.class }) MetricFilterConfiguration.class })
public class ServiceAutoConfiguration extends WebMvcConfigurationSupport { public class ServiceAutoConfiguration extends WebMvcConfigurationSupport {
@Override @Override
@ -55,11 +56,12 @@ public class ServiceAutoConfiguration extends WebMvcConfigurationSupport {
} }
/* /*
* ContainerProperties has to be declared in a non-conditional bean, so that it gets * ServerProperties has to be declared in a non-conditional bean, so that it gets
* added to the context early enough * added to the context early enough
*/ */
@EnableConfigurationProperties(ContainerProperties.class) @EnableConfigurationProperties({ ServerProperties.class,
public static class ContainerPropertiesConfiguration { ManagementServerProperties.class })
public static class ServerPropertiesConfiguration {
} }
} }

View File

@ -34,7 +34,7 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration @Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnMissingBean({ ShutdownEndpoint.class }) @ConditionalOnMissingBean({ ShutdownEndpoint.class })
public class ShutdownAutoConfiguration { public class ShutdownConfiguration {
@Bean @Bean
public ShutdownEndpoint shutdownEndpoint() { public ShutdownEndpoint shutdownEndpoint() {

View File

@ -41,25 +41,25 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration @Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnMissingBean({ TraceEndpoint.class }) @ConditionalOnMissingBean({ TraceEndpoint.class })
public class TraceAutoConfiguration { public class TraceConfiguration {
@Autowired(required = false) @Autowired
private TraceRepository traceRepository = new InMemoryTraceRepository(); private TraceRepository traceRepository;
@Bean
@ConditionalOnMissingBean(TraceRepository.class)
protected TraceRepository traceRepository() {
return this.traceRepository;
}
@Configuration @Configuration
@ConditionalOnClass(SecurityFilterChain.class) @ConditionalOnClass(SecurityFilterChain.class)
public static class SecurityFilterPostProcessorConfiguration { public static class SecurityFilterPostProcessorConfiguration {
@Autowired @Autowired(required = false)
private TraceRepository traceRepository; private TraceRepository traceRepository = new InMemoryTraceRepository();
@Value("${container.dump_requests:false}") @Bean
@ConditionalOnMissingBean(TraceRepository.class)
protected TraceRepository traceRepository() {
return this.traceRepository;
}
@Value("${management.dump_requests:false}")
private boolean dumpRequests; private boolean dumpRequests;
@Bean @Bean

View File

@ -38,7 +38,7 @@ import org.springframework.web.servlet.DispatcherServlet;
@Configuration @Configuration
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class }) @ConditionalOnClass({ Servlet.class, DispatcherServlet.class })
@ConditionalOnMissingBean({ VarzEndpoint.class }) @ConditionalOnMissingBean({ VarzEndpoint.class })
public class VarzAutoConfiguration { public class VarzConfiguration {
@Autowired @Autowired
private MetricRepository repository; private MetricRepository repository;

View File

@ -16,6 +16,9 @@
package org.springframework.bootstrap.service.annotation; package org.springframework.bootstrap.service.annotation;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.bootstrap.context.annotation.ConfigurationProperties; import org.springframework.bootstrap.context.annotation.ConfigurationProperties;
@ -25,11 +28,13 @@ import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
/** /**
* Import selector that sets up binding of external properties to configuration classes (see * Import selector that sets up binding of external properties to configuration classes
* {@link ConfigurationProperties}). It either registers a {@link ConfigurationProperties} bean or not, depending on * (see {@link ConfigurationProperties}). It either registers a
* whether the enclosing {@link EnableConfigurationProperties} explicitly declares one. If none is declared then a bean * {@link ConfigurationProperties} bean or not, depending on whether the enclosing
* post processor will still kick in for any beans annotated as external configuration. If one is declared then it a * {@link EnableConfigurationProperties} explicitly declares one. If none is declared then
* bean definition is registered with id equal to the class name (thus an application context usually only contains one * a bean post processor will still kick in for any beans annotated as external
* configuration. If one is declared then it a bean definition is registered with id equal
* to the class name (thus an application context usually only contains one
* {@link ConfigurationProperties} bean of each unique type). * {@link ConfigurationProperties} bean of each unique type).
* *
* @author Dave Syer * @author Dave Syer
@ -42,21 +47,39 @@ public class ConfigurationPropertiesImportSelector implements ImportSelector {
EnableConfigurationProperties.class.getName(), false); EnableConfigurationProperties.class.getName(), false);
Object type = attributes.getFirst("value"); Object type = attributes.getFirst("value");
if (type == void.class) { if (type == void.class) {
return new String[] { ConfigurationPropertiesBindingConfiguration.class.getName() }; return new String[] { ConfigurationPropertiesBindingConfiguration.class
.getName() };
} }
return new String[] { ConfigurationPropertiesBeanRegistrar.class.getName(), return new String[] { ConfigurationPropertiesBeanRegistrar.class.getName(),
ConfigurationPropertiesBindingConfiguration.class.getName() }; ConfigurationPropertiesBindingConfiguration.class.getName() };
} }
public static class ConfigurationPropertiesBeanRegistrar implements ImportBeanDefinitionRegistrar { public static class ConfigurationPropertiesBeanRegistrar implements
ImportBeanDefinitionRegistrar {
@Override @Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { public void registerBeanDefinitions(AnnotationMetadata metadata,
MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( BeanDefinitionRegistry registry) {
EnableConfigurationProperties.class.getName(), false); MultiValueMap<String, Object> attributes = metadata
Class<?> type = (Class<?>) attributes.getFirst("value"); .getAllAnnotationAttributes(
registry.registerBeanDefinition(type.getName(), BeanDefinitionBuilder.genericBeanDefinition(type) EnableConfigurationProperties.class.getName(), false);
.getBeanDefinition()); List<Class<?>> types = collectClasses(attributes.get("value"));
for (Class<?> type : types) {
registry.registerBeanDefinition(type.getName(), BeanDefinitionBuilder
.genericBeanDefinition(type).getBeanDefinition());
}
}
private List<Class<?>> collectClasses(List<Object> list) {
ArrayList<Class<?>> result = new ArrayList<Class<?>>();
for (Object object : list) {
for (Object value : (Object[]) object) {
if (value instanceof Class) {
result.add((Class<?>) value);
}
}
}
return result;
} }
} }

View File

@ -33,6 +33,6 @@ import org.springframework.context.annotation.Import;
@Import(ConfigurationPropertiesImportSelector.class) @Import(ConfigurationPropertiesImportSelector.class)
public @interface EnableConfigurationProperties { public @interface EnableConfigurationProperties {
Class<?> value() default void.class; Class<?>[] value() default { void.class };
} }

View File

@ -0,0 +1,62 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.bootstrap.service.properties;
import javax.validation.constraints.NotNull;
import org.springframework.bootstrap.context.annotation.ConfigurationProperties;
/**
* Properties for the management server (e.g. port and path settings).
*
* @author Dave Syer
*/
@ConfigurationProperties(name = "management", ignoreUnknownFields = false)
public class ManagementServerProperties {
private int port = 8080;
@NotNull
private String contextPath = "";
private boolean allowShutdown = false;
public boolean isAllowShutdown() {
return this.allowShutdown;
}
public void setAllowShutdown(boolean allowShutdown) {
this.allowShutdown = allowShutdown;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public String getContextPath() {
return this.contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
}

View File

@ -18,34 +18,31 @@ package org.springframework.bootstrap.service.properties;
import java.io.File; import java.io.File;
import javax.validation.constraints.NotNull;
import org.springframework.bootstrap.context.annotation.ConfigurationProperties; import org.springframework.bootstrap.context.annotation.ConfigurationProperties;
/** /**
* Properties for the web container (e.g. port and path settings). * Properties for the web server (e.g. port and path settings).
* *
* @author Dave Syer * @author Dave Syer
*/ */
@ConfigurationProperties(name = "container", ignoreUnknownFields = false) @ConfigurationProperties(name = "server", ignoreUnknownFields = false)
public class ContainerProperties { public class ServerProperties {
private int port = 8080; private int port = 8080;
private int managementPort = this.port; @NotNull
private String contextPath = "";
private String contextPath;
private boolean allowShutdown = false;
private Tomcat tomcat = new Tomcat(); private Tomcat tomcat = new Tomcat();
private boolean dumpRequests;
public Tomcat getTomcat() { public Tomcat getTomcat() {
return this.tomcat; return this.tomcat;
} }
public String getContextPath() { public String getContextPath() {
return this.contextPath == null ? "" : this.contextPath; return this.contextPath;
} }
public void setContextPath(String contextPath) { public void setContextPath(String contextPath) {
@ -60,30 +57,6 @@ public class ContainerProperties {
this.port = port; this.port = port;
} }
public int getManagementPort() {
return this.managementPort;
}
public void setManagementPort(int managementPort) {
this.managementPort = managementPort;
}
public boolean isAllowShutdown() {
return this.allowShutdown;
}
public void setAllowShutdown(boolean allowShutdown) {
this.allowShutdown = allowShutdown;
}
public boolean isDumpRequests() {
return this.dumpRequests;
}
public void setDumpRequests(boolean dumpRequests) {
this.dumpRequests = dumpRequests;
}
public static class Tomcat { public static class Tomcat {
private String accessLogPattern; private String accessLogPattern;

View File

@ -22,7 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.bootstrap.service.properties.ContainerProperties; import org.springframework.bootstrap.service.properties.ManagementServerProperties;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
@ -46,7 +46,7 @@ public class ShutdownEndpoint implements ApplicationContextAware,
private ConfigurableApplicationContext context; private ConfigurableApplicationContext context;
@Autowired @Autowired
private ContainerProperties configuration = new ContainerProperties(); private ManagementServerProperties configuration = new ManagementServerProperties();
private boolean shuttingDown = false; private boolean shuttingDown = false;