Skip to content

Commit

Permalink
Code polished
Browse files Browse the repository at this point in the history
  • Loading branch information
stojsavljevic committed Nov 30, 2023
1 parent 00859bd commit 018adce
Show file tree
Hide file tree
Showing 24 changed files with 142 additions and 194 deletions.
3 changes: 2 additions & 1 deletion multi-ctx-app-builder/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ This sample application demonstrates creation of three contexts:
2. Child web context #1 on separate port [http://localhost:8080/first/](http://localhost:8080/first/)
3. Child web context #2 on separate port [http://localhost:8081/second/](http://localhost:8081/second/)

Contexts are created using Spring Boot's Fluent builder API (http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html#boot-features-fluent-builder-api):
Contexts are created using Spring Boot's [Fluent builder API](https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.fluent-builder-api):

```
public static void main(String[] args) {
new SpringApplicationBuilder().sources(ParentCtxConfig.class)
Expand Down
19 changes: 0 additions & 19 deletions multi-ctx-app-builder/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,4 @@
<name>multi-ctx-app-builder</name>
<description>Spring Boot Multi Context Application using SpringApplicationBuilder</description>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public class ChildFirstCtxConfig {

@Bean(name = "child_first_bean")
public String getChildFirstBean() {
String getChildFirstBean() {
return "child_first_bean";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public class ChildSecondCtxConfig {

@Bean(name = "child_second_bean")
public String getChildSecondBean() {
String getChildSecondBean() {
return "child_second_bean";
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package com.alex.demo.ctx.parent;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SpringBootConfiguration
public class ParentCtxConfig {

@Bean(name = "parent_bean")
public String getParentBean() {
String getParentBean() {
return "parent_bean";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -14,7 +13,6 @@
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.alex.demo.ctx.child.first.ChildFirstCtxConfig;

Expand All @@ -24,7 +22,6 @@
* class for parent context only because we need one bean from there.
*
*/
@ExtendWith(SpringExtension.class)
@ContextHierarchy(@ContextConfiguration(name = "child", classes = ChildFirstCtxConfig.class))
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
Expand Down Expand Up @@ -57,7 +54,7 @@ void testChildFirstNotExists() throws Exception {

Assertions.assertAll("Error response for non-existing URL on the first child context is wrong!",
() -> Assertions.assertEquals("Not Found", response.get("error")),
() -> Assertions.assertEquals(new Integer(404), response.get("status")),
() -> Assertions.assertEquals(404, response.get("status")),
() -> Assertions.assertEquals("/first/dummy", response.get("path"))
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -14,7 +13,6 @@
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.alex.demo.ctx.child.second.ChildSecondCtxConfig;

Expand All @@ -24,7 +22,6 @@
* class for parent context only because we need one bean from there.
*
*/
@ExtendWith(SpringExtension.class)
@ContextHierarchy(@ContextConfiguration(name = "child", classes = ChildSecondCtxConfig.class))
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
Expand Down Expand Up @@ -57,7 +54,7 @@ void testChildSecondNotExists() throws Exception {

Assertions.assertAll("Error response for non-existing URL on the second child context is wrong!",
() -> Assertions.assertEquals("Not Found", response.get("error")),
() -> Assertions.assertEquals(new Integer(404), response.get("status")),
() -> Assertions.assertEquals(404, response.get("status")),
() -> Assertions.assertEquals("/second/dummy", response.get("path"))
);
}
Expand Down
4 changes: 3 additions & 1 deletion multi-ctx-app-embed/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@ This sample application demonstrates creation of three contexts:

Child context is type `org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext`.
It is created using Java configuration:

```
@Bean
public AnnotationConfigServletWebServerApplicationContext createChildContext(ApplicationContext parentContext) {
AnnotationConfigServletWebServerApplicationContext childContext = new AnnotationConfigServletWebServerApplicationContext();
AnnotationConfigServletWebServerApplicationContext childContext = (AnnotationConfigServletWebServerApplicationContext) ApplicationContextFactory.DEFAULT
.create(WebApplicationType.SERVLET);
...
return childContext;
}
Expand Down
19 changes: 0 additions & 19 deletions multi-ctx-app-embed/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,4 @@
<name>multi-ctx-app-embed</name>
<description>Spring Boot Multi Context Application using AnnotationConfigEmbeddedWebApplicationContext</description>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletRegistrationBean;
Expand Down Expand Up @@ -59,28 +58,28 @@
public class ChildCtxConfig {

@Bean(name = "child_bean")
public String getChildBean() {
String getChildBean() {
return "child_bean";
}

@Value("${server.port:8888}")
int parentProperty;
@Value("${child.server.port}")
int childContextServerPort;

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}

@Bean
@ConditionalOnBean(ErrorAttributes.class)
public ManagementErrorEndpoint errorEndpoint(ErrorAttributes errorAttributes) {
return new ManagementErrorEndpoint(errorAttributes, new ErrorProperties());
ManagementErrorEndpoint errorEndpoint(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
return new ManagementErrorEndpoint(errorAttributes, serverProperties.getError());
}

@Profile("parent")
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// Ensure the parent configuration does not leak down to us
dispatcherServlet.setDetectAllHandlerAdapters(false);
Expand All @@ -92,19 +91,19 @@ public DispatcherServlet dispatcherServlet() {

@Profile("parent")
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
public DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) {
DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) {
return new DispatcherServletRegistrationBean(dispatcherServlet, "/");
}

@Profile("parent")
@Bean(name = DispatcherServlet.HANDLER_MAPPING_BEAN_NAME)
public CompositeHandlerMapping compositeHandlerMapping() {
CompositeHandlerMapping compositeHandlerMapping() {
return new CompositeHandlerMapping();
}

@Profile("parent")
@Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME)
public CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) {
CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) {
return new CompositeHandlerAdapter(beanFactory);
}

Expand All @@ -117,12 +116,12 @@ CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() {
@Profile("parent")
@Bean
@ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class })
public RequestContextFilter requestContextFilter() {
RequestContextFilter requestContextFilter() {
return new OrderedRequestContextFilter();
}

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

@Autowired
private ListableBeanFactory beanFactory;
Expand All @@ -132,7 +131,7 @@ public void customize(TomcatServletWebServerFactory factory) {
ServerProperties server = BeanFactoryUtils.beanOfTypeIncludingAncestors(this.beanFactory,
ServerProperties.class);

factory.setPort(parentProperty);
factory.setPort(childContextServerPort);
factory.addErrorPages(new ErrorPage(server.getError().getPath()));
factory.setServerHeader(server.getServerHeader());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class ChildCtxController {
@Qualifier("child_bean")
String childBean;

@Value("${common.property:null}")
@Value("${custom.property.parent:null}")
String parentProperty;

@Value("${custom.property.child}")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
package com.alex.demo.ctx.parent;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationContextFactory;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

import com.alex.demo.ctx.child.ChildCtxConfig;
Expand All @@ -16,23 +22,35 @@ public class ParentCtxConfig {
Environment environment;

@Bean(name = "parent_bean")
public String getParentBean() {
String getParentBean() {
return "parent_bean";
}

/**
* @see org.springframework.boot.actuate.autoconfigure.web.servlet.ServletManagementContextFactory#createManagementContext(ApplicationContext, Class...)
* @see org.springframework.boot.actuate.autoconfigure.web.server.ChildManagementContextInitializer#createManagementContext()
* @param parentContext
* @return
*/
@Bean
public AnnotationConfigServletWebServerApplicationContext createChildContext(ApplicationContext parentContext) {
AnnotationConfigServletWebServerApplicationContext childContext = new AnnotationConfigServletWebServerApplicationContext();
ConfigurableApplicationContext createManagementContext(ApplicationContext parentContext) {

AnnotationConfigServletWebServerApplicationContext childContext = (AnnotationConfigServletWebServerApplicationContext) ApplicationContextFactory.DEFAULT
.create(WebApplicationType.SERVLET);
ConfigurableEnvironment childEnvironment = ApplicationContextFactory.DEFAULT
.createEnvironment(WebApplicationType.SERVLET);
childContext.setEnvironment(childEnvironment);

if (parentContext.getEnvironment() instanceof ConfigurableEnvironment configurableEnvironment) {
childEnvironment.setConversionService((configurableEnvironment).getConversionService());
}

if (hasProfile("parent")) {
childContext.setParent(parentContext);
}

childContext.setServerNamespace("first");
childContext.setClassLoader(parentContext.getClassLoader());

childContext.setNamespace("first");
childContext.setId(parentContext.getId() + ":first");

Expand All @@ -43,11 +61,6 @@ public AnnotationConfigServletWebServerApplicationContext createChildContext(App
}

boolean hasProfile(String profileName) {
for (String profile : environment.getActiveProfiles()) {
if (profile.equals(profileName)) {
return true;
}
}
return false;
return Arrays.stream(environment.getActiveProfiles()).anyMatch(profile -> profile.equals(profileName));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class ParentCtxController {
@Qualifier("child_bean")
String childBean;

@Value("${common.property:null}")
@Value("${custom.property.parent:null}")
String parentProperty;

@Value("${custom.property.child:null}")
Expand Down
5 changes: 3 additions & 2 deletions multi-ctx-app-embed/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
common:
property: common_prop
custom:
property:
parent: parent_prop

management:
server:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
custom.property.child=prop_child
server.port=8082
child.server.port=8082
Loading

0 comments on commit 018adce

Please sign in to comment.