move spring-all/spring43 to spring-4 module

* WebMvcConfigurer default methods are available only in Spring 5+
  changed AttributeAnnotationConfiguration to
  extend WebMvcConfigurerAdapter
This commit is contained in:
Denis
2019-10-06 11:26:14 +02:00
committed by Denis
parent f8ca31c99b
commit 6f6f891355
42 changed files with 27 additions and 18 deletions

View File

@@ -2,3 +2,4 @@
- [A Guide to Flips for Spring](http://www.baeldung.com/flips-spring)
- [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari)
- [Spring JSON-P with Jackson](http://www.baeldung.com/spring-jackson-jsonp)
- [Whats New in Spring 4.3?](http://www.baeldung.com/whats-new-in-spring-4-3)

View File

@@ -67,6 +67,27 @@
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>${easymock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>${hsqldb.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -88,6 +109,8 @@
<properties>
<start-class>com.baeldung.flips.ApplicationConfig</start-class>
<flips-web.version>1.0.1</flips-web.version>
<easymock.version>3.6</easymock.version>
<hsqldb.version>2.4.0</hsqldb.version>
</properties>
</project>

View File

@@ -0,0 +1,14 @@
package org.baeldung.spring43.attributeannotations;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/test")
public class AttributeAnnotationsTestController {
@GetMapping
public String get(@SessionAttribute String login, @RequestAttribute String query) {
return String.format("login = %s, query = %s", login, query);
}
}

View File

@@ -0,0 +1,17 @@
package org.baeldung.spring43.attributeannotations;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class ParamInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
request.getSession().setAttribute("login", "john");
request.setAttribute("query", "invoices");
return super.preHandle(request, response, handler);
}
}

View File

@@ -0,0 +1,28 @@
package org.baeldung.spring43.cache;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
private static final Logger log = LoggerFactory.getLogger(Foo.class);
private static final AtomicInteger instanceCount = new AtomicInteger(0);
private final int instanceNum;
public Foo() {
instanceNum = instanceCount.incrementAndGet();
}
public static int getInstanceCount() {
return instanceCount.get();
}
public void printInstanceNumber() {
log.info("Foo instance number: {}", instanceNum);
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.spring43.cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class FooService {
@Cacheable(cacheNames = "foos", sync = true)
public Foo getFoo(String id) {
return new Foo();
}
}

View File

@@ -0,0 +1,5 @@
package org.baeldung.spring43.composedmapping;
public class Appointment {
}

View File

@@ -0,0 +1,9 @@
package org.baeldung.spring43.composedmapping;
import java.util.Map;
public interface AppointmentService {
Map<String, Appointment> getAppointmentsForToday();
}

View File

@@ -0,0 +1,31 @@
package org.baeldung.spring43.composedmapping;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.logging.log4j.Logger;
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
private AppointmentService appointmentService;
@Autowired
private Logger logger;
@Autowired
public AppointmentsController(AppointmentService appointmentService) {
this.appointmentService = appointmentService;
}
@GetMapping
public Map<String, Appointment> get() {
logger.info("Getting appointments...");
return appointmentService.getAppointmentsForToday();
}
}

View File

@@ -0,0 +1,5 @@
package org.baeldung.spring43.ctor;
public class FooRepository {
}

View File

@@ -0,0 +1,15 @@
package org.baeldung.spring43.ctor;
public class FooService {
private final FooRepository repository;
public FooService(FooRepository repository) {
this.repository = repository;
}
public FooRepository getRepository() {
return repository;
}
}

View File

@@ -0,0 +1,18 @@
package org.baeldung.spring43.defaultmethods;
import java.time.LocalDate;
public class DateHolder implements IDateHolder {
private LocalDate localDate;
@Override
public LocalDate getLocalDate() {
return localDate;
}
@Override
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
}

View File

@@ -0,0 +1,16 @@
package org.baeldung.spring43.defaultmethods;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public interface IDateHolder {
LocalDate getLocalDate();
void setLocalDate(LocalDate localDate);
default void setStringDate(String stringDate) {
setLocalDate(LocalDate.parse(stringDate, DateTimeFormatter.ofPattern("dd.MM.yyyy")));
}
}

View File

@@ -0,0 +1,8 @@
package org.baeldung.spring43.depresolution;
import org.springframework.stereotype.Repository;
@Repository
public class FooRepository {
}

View File

@@ -0,0 +1,18 @@
package org.baeldung.spring43.depresolution;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;
@Service
public class FooService {
private final FooRepository repository;
public FooService(ObjectProvider<FooRepository> repositoryProvider) {
this.repository = repositoryProvider.getIfUnique();
}
public FooRepository getRepository() {
return repository;
}
}

View File

@@ -0,0 +1,10 @@
package org.baeldung.spring43.scopeannotations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.ApplicationScope;
@Component
@ApplicationScope
public class AppPreferences extends InstanceCountingService {
}

View File

@@ -0,0 +1,15 @@
package org.baeldung.spring43.scopeannotations;
import java.util.concurrent.atomic.AtomicInteger;
public class InstanceCountingService {
private static final AtomicInteger instanceCount = new AtomicInteger(0);
private final int instanceNumber = instanceCount.incrementAndGet();
public int getInstanceNumber() {
return instanceNumber;
}
}

View File

@@ -0,0 +1,10 @@
package org.baeldung.spring43.scopeannotations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;
@Component
@RequestScope
public class LoginAction extends InstanceCountingService {
}

View File

@@ -0,0 +1,36 @@
package org.baeldung.spring43.scopeannotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/appointments")
public class ScopeTestController {
@Autowired
private LoginAction loginAction;
@Autowired
private UserPreferences userPreferences;
@Autowired
private AppPreferences appPreferences;
@GetMapping("/request")
public String getRequestNumber() {
return Integer.toString(loginAction.getInstanceNumber());
}
@GetMapping("/session")
public String getSessionNumber() {
return Integer.toString(userPreferences.getInstanceNumber());
}
@GetMapping("/application")
public String getApplicationNumber() {
return Integer.toString(appPreferences.getInstanceNumber());
}
}

View File

@@ -0,0 +1,10 @@
package org.baeldung.spring43.scopeannotations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
public class UserPreferences extends InstanceCountingService {
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dateHolder" class="org.baeldung.spring43.defaultmethods.DateHolder">
<property name="stringDate" value="15.10.1982"/>
</bean>
</beans>

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.baeldung.spring43.ctor.FooRepository"/>
<bean class="org.baeldung.spring43.ctor.FooService"/>
</beans>

View File

@@ -0,0 +1,30 @@
package org.baeldung.spring43.attributeannotations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan
@EnableWebMvc
public class AttributeAnnotationConfiguration extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ParamInterceptor());
}
}

View File

@@ -0,0 +1,39 @@
package org.baeldung.spring43.attributeannotations;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ContextConfiguration(classes = AttributeAnnotationConfiguration.class)
@WebAppConfiguration
public class AttributeAnnotationIntegrationTest extends AbstractJUnit4SpringContextTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenInterceptorAddsRequestAndSessionParams_thenParamsInjectedWithAttributesAnnotations() throws Exception {
String result = this.mockMvc.perform(get("/test").accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
Assert.assertEquals("login = john, query = invoices", result);
}
}

View File

@@ -0,0 +1,25 @@
package org.baeldung.spring43.cache;
import java.util.Collections;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
@EnableCaching
public class CacheRefinementsConfiguration {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches(Collections.singletonList(new ConcurrentMapCache("foos")));
return manager;
}
}

View File

@@ -0,0 +1,31 @@
package org.baeldung.spring43.cache;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertEquals;
@ContextConfiguration(classes = CacheRefinementsConfiguration.class)
public class CacheRefinementsIntegrationTest extends AbstractJUnit4SpringContextTests {
private ExecutorService executorService = Executors.newFixedThreadPool(10);
@Autowired
private FooService service;
@Test
public void whenMultipleThreadsExecuteCacheableMethodWithSyncTrue_thenMethodIsExecutedOnlyOnce() throws InterruptedException {
for (int i = 0; i < 10; i++) {
executorService.execute(() -> service.getFoo("test").printInstanceNumber());
}
executorService.awaitTermination(1, TimeUnit.SECONDS);
assertEquals(1, Foo.getInstanceCount());
}
}

View File

@@ -0,0 +1,46 @@
package org.baeldung.spring43.composedmapping;
import java.util.Collections;
import org.easymock.EasyMock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.beans.factory.InjectionPoint;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Scope;
import static org.easymock.EasyMock.replay;
@Configuration
@ComponentScan
@EnableWebMvc
public class ComposedMappingConfiguration {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Bean
public AppointmentService appointmentBook() {
AppointmentService book = EasyMock.mock(AppointmentService.class);
EasyMock.expect(book.getAppointmentsForToday()).andReturn(Collections.emptyMap());
replay(book);
return book;
}
@Bean
@Scope("prototype")
public Logger logger(InjectionPoint injectionPoint) {
return LogManager.getLogger(injectionPoint.getField().getDeclaringClass());
}
}

View File

@@ -0,0 +1,41 @@
package org.baeldung.spring43.composedmapping;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.easymock.EasyMock.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ContextConfiguration(classes = ComposedMappingConfiguration.class)
@WebAppConfiguration
public class ComposedMappingIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private AppointmentService appointmentService;
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenRequestingMethodWithGetMapping_thenReceiving200Answer() throws Exception {
this.mockMvc.perform(get("/appointments").accept(MediaType.ALL)).andExpect(status().isOk());
verify(appointmentService);
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.spring43.ctor;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(classes = { FooRepositoryConfiguration.class, FooServiceConfiguration.class })
public class ConfigurationConstructorInjectionIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
public FooService fooService;
@Test
public void whenSingleCtorInConfiguration_thenContextLoadsNormally() {
assertNotNull(fooService.getRepository());
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.spring43.ctor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FooRepositoryConfiguration {
@Bean
public FooRepository fooRepository() {
return new FooRepository();
}
}

View File

@@ -0,0 +1,19 @@
package org.baeldung.spring43.ctor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FooServiceConfiguration {
private final FooRepository repository;
public FooServiceConfiguration(FooRepository repository) {
this.repository = repository;
}
@Bean
public FooService fooService() {
return new FooService(this.repository);
}
}

View File

@@ -0,0 +1,21 @@
package org.baeldung.spring43.ctor;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration("classpath:implicit-ctor-context.xml")
public class ImplicitConstructorIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private FooService fooService;
@Test
public void whenBeanWithoutAutowiredCtor_thenInjectIntoSingleCtor() {
assertNotNull(fooService.getRepository());
}
}

View File

@@ -0,0 +1,23 @@
package org.baeldung.spring43.defaultmethods;
import java.time.LocalDate;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertEquals;
@ContextConfiguration("classpath:defaultmethods-context.xml")
public class DefaultMethodsInjectionIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private IDateHolder dateHolder;
@Test
public void whenInjectingToDefaultInterfaceMethod_thenInjectionShouldHappen() {
assertEquals(LocalDate.of(1982, 10, 15), dateHolder.getLocalDate());
}
}

View File

@@ -0,0 +1,22 @@
package org.baeldung.spring43.defaultmethods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
public interface ITransactionalUnitTest {
Logger log = LoggerFactory.getLogger(ITransactionalUnitTest.class);
@BeforeTransaction
default void beforeTransaction() {
log.info("Opening transaction");
}
@AfterTransaction
default void afterTransaction() {
log.info("Closing transaction");
}
}

View File

@@ -0,0 +1,14 @@
package org.baeldung.spring43.defaultmethods;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
@ContextConfiguration(classes = TransactionalTestConfiguration.class)
public class TransactionalIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests implements ITransactionalUnitTest {
@Test
public void whenDefaultMethodAnnotatedWithBeforeTransaction_thenDefaultMethodIsExecuted() {
}
}

View File

@@ -0,0 +1,29 @@
package org.baeldung.spring43.defaultmethods;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;
import org.springframework.transaction.PlatformTransactionManager;
@Configuration
public class TransactionalTestConfiguration {
@Bean
public DataSource getDataSource() {
SimpleDriverDataSource simpleDriverDataSource = new SimpleDriverDataSource();
simpleDriverDataSource.setDriverClass(org.hsqldb.jdbcDriver.class);
simpleDriverDataSource.setUrl("jdbc:hsqldb:mem:app-db");
simpleDriverDataSource.setUsername("sa");
simpleDriverDataSource.setPassword("");
return simpleDriverDataSource;
}
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(getDataSource());
}
}

View File

@@ -0,0 +1,9 @@
package org.baeldung.spring43.depresolution;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan
public class ObjectProviderConfiguration {
}

View File

@@ -0,0 +1,23 @@
package org.baeldung.spring43.depresolution;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import static org.junit.Assert.assertNotNull;
@ContextConfiguration(classes = ObjectProviderConfiguration.class)
public class ObjectProviderIntegrationTest extends AbstractJUnit4SpringContextTests {
@Autowired
private FooService fooService;
@Test
public void whenArgumentIsObjectProvider_thenObjectProviderInjected() {
assertNotNull(fooService.getRepository());
}
}

View File

@@ -0,0 +1,23 @@
package org.baeldung.spring43.scopeannotations;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@ComponentScan
@EnableWebMvc
public class ScopeAnnotationsConfiguration {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

View File

@@ -0,0 +1,74 @@
package org.baeldung.spring43.scopeannotations;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ContextConfiguration(classes = ScopeAnnotationsConfiguration.class)
@WebAppConfiguration
public class ScopeAnnotationsIntegrationTest extends AbstractJUnit4SpringContextTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void whenDifferentRequests_thenDifferentInstancesOfRequestScopedBeans() throws Exception {
MockHttpSession session = new MockHttpSession();
String requestScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String requestScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/request").session(session).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertNotEquals(requestScopedServiceInstanceNumber1, requestScopedServiceInstanceNumber2);
}
@Test
public void whenDifferentSessions_thenDifferentInstancesOfSessionScopedBeans() throws Exception {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String sessionScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String sessionScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/session").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String sessionScopedServiceInstanceNumber3 = this.mockMvc.perform(get("/appointments/session").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber2);
assertNotEquals(sessionScopedServiceInstanceNumber1, sessionScopedServiceInstanceNumber3);
}
@Test
public void whenDifferentSessionsAndRequests_thenAlwaysSingleApplicationScopedBean() throws Exception {
MockHttpSession session1 = new MockHttpSession();
MockHttpSession session2 = new MockHttpSession();
String applicationScopedServiceInstanceNumber1 = this.mockMvc.perform(get("/appointments/application").session(session1).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
String applicationScopedServiceInstanceNumber2 = this.mockMvc.perform(get("/appointments/application").session(session2).accept(MediaType.ALL)).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
assertEquals(applicationScopedServiceInstanceNumber1, applicationScopedServiceInstanceNumber2);
}
}