Merge pull request #11587 from kwoyke/JAVA-8794

JAVA-8794: Upgrade to Spring Boot 2.6.1
This commit is contained in:
kwoyke 2021-12-16 14:16:37 +01:00 committed by GitHub
commit 7782e86856
92 changed files with 1211 additions and 97 deletions

View File

@ -2,12 +2,21 @@ package com.baeldung.java9.modules;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.*; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.module.ModuleDescriptor; import java.lang.module.ModuleDescriptor;
import java.lang.module.ModuleDescriptor.*;
import java.lang.module.ModuleDescriptor.Builder;
import java.lang.module.ModuleDescriptor.Exports;
import java.lang.module.ModuleDescriptor.Opens;
import java.lang.module.ModuleDescriptor.Provides;
import java.lang.module.ModuleDescriptor.Requires;
import java.sql.Date; import java.sql.Date;
import java.sql.Driver; import java.sql.Driver;
import java.util.HashMap; import java.util.HashMap;
@ -16,7 +25,7 @@ import java.util.stream.Collectors;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.Ignore;
public class ModuleAPIUnitTest { public class ModuleAPIUnitTest {
@ -28,14 +37,9 @@ public class ModuleAPIUnitTest {
@Before @Before
public void setUp() { public void setUp() {
Class<HashMap> hashMapClass = HashMap.class; javaBaseModule = HashMap.class.getModule();
javaBaseModule = hashMapClass.getModule(); javaSqlModule = Date.class.getModule();
module = Person.class.getModule();
Class<Date> dateClass = Date.class;
javaSqlModule = dateClass.getModule();
Class<Person> personClass = Person.class;
module = personClass.getModule();
} }
@Test @Test
@ -111,7 +115,6 @@ public class ModuleAPIUnitTest {
} }
@Test @Test
@Ignore // fixing in http://team.baeldung.com/browse/JAVA-8679
public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() { public void givenModules_whenAccessingModuleDescriptorProvides_thenProvidesAreReturned() {
Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides(); Set<Provides> javaBaseProvides = javaBaseModule.getDescriptor().provides();
Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides(); Set<Provides> javaSqlProvides = javaSqlModule.getDescriptor().provides();
@ -120,7 +123,7 @@ public class ModuleAPIUnitTest {
.map(Provides::service) .map(Provides::service)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
assertThat(javaBaseProvidesService, contains("java.nio.file.spi.FileSystemProvider")); assertThat(javaBaseProvidesService, hasItem("java.nio.file.spi.FileSystemProvider"));
assertThat(javaSqlProvides, empty()); assertThat(javaSqlProvides, empty());
} }
@ -137,10 +140,9 @@ public class ModuleAPIUnitTest {
@Test @Test
public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() { public void givenModules_whenAccessingModuleDescriptorUses_thenUsesAreReturned() {
Set<String> javaBaseUses = javaBaseModule.getDescriptor().uses();
Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses(); Set<String> javaSqlUses = javaSqlModule.getDescriptor().uses();
assertThat(javaSqlUses, contains("java.sql.Driver")); assertThat(javaSqlUses, hasItem("java.sql.Driver"));
} }
@Test @Test

View File

@ -0,0 +1,26 @@
package com.baeldung.implicitsuperconstructorundefined;
public class Employee extends Person {
private Double salary;
public Employee(String name, Integer age, Double salary) {
// comment this super call to see the error.
super(name, age);
this.salary = salary;
}
public Employee(Double salary) {
super();
this.salary = salary;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.implicitsuperconstructorundefined;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
// comment this constructor to see the error.
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}

View File

@ -5,4 +5,4 @@ This module contains articles about types in Java
### Relevant Articles: ### Relevant Articles:
- [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array) - [Convert an Array of Primitives to an Array of Objects](https://www.baeldung.com/java-primitive-array-to-object-array)
- [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-find-enum-by-criteria) - [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values)

View File

@ -0,0 +1,13 @@
package com.baeldung.lombok.with;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.With;
@Getter
@AllArgsConstructor
public abstract class Device {
private final String serial;
@With
private final boolean isInspected;
}

View File

@ -0,0 +1,16 @@
package com.baeldung.lombok.with;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.With;
@Getter
@AllArgsConstructor
public class Holder {
@With
private String variableA;
@With
private String _variableB;
@With
private String $variableC;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.lombok.with;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import lombok.With;
@With
@AllArgsConstructor
public class ImprovedUser {
@NonNull
private final String username;
@NonNull
private final String emailAddress;
}

View File

@ -0,0 +1,13 @@
package com.baeldung.lombok.with;
public class KioskDevice extends Device {
public KioskDevice(String serial, boolean isInspected) {
super(serial, isInspected);
}
@Override
public Device withInspected(boolean isInspected) {
return new KioskDevice(getSerial(), isInspected);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.lombok.with;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.With;
@Getter
@AllArgsConstructor
public class Stock {
@With
private String sku;
private int stockCount;
public Stock withSku(String sku) {
return new Stock("mod-" + sku, stockCount);
}
public Stock withSKU(String... sku) {
return sku == null || sku.length == 0 ?
new Stock("unknown", stockCount) :
new Stock("mod-" + sku[0], stockCount);
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.lombok.with;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.With;
@Getter
@AllArgsConstructor
public class User {
private final String username;
private final String emailAddress;
@With
private final boolean isAuthenticated;
}

View File

@ -0,0 +1,24 @@
package com.baeldung.lombok.with;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotSame;
public class HolderUnitTest {
@Test
public void whenWithMethodsGenerated_thenUsable() {
Holder value = new Holder("a", "b");
Holder valueModifiedA = value.withVariableA("mod-a");
Holder valueModifiedB = value.with_variableB("mod-b");
// Holder valueModifiedC = value.with$VariableC("mod-c"); not possible
assertNotSame(valueModifiedA, value);
assertNotSame(valueModifiedB, value);
assertEquals("mod-a", valueModifiedA.getVariableA());
assertEquals("mod-b", valueModifiedB.get_variableB());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.lombok.with;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ImprovedUserUnitTest {
@Test
public void whenUsernameNull_thenException() {
ImprovedUser user = new ImprovedUser("testuser", "test@mail.com");
assertThrows(NullPointerException.class, () -> user.withUsername(null));
}
@Test
public void whenEmailNull_thenException() {
ImprovedUser user = new ImprovedUser("testuser", "test@mail.com");
assertThrows(NullPointerException.class, () -> user.withEmailAddress(null));
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.lombok.with;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class KioskDeviceWithUnitTest {
@Test
public void whenDeviceInspected_thenClonedAndUpdated() {
KioskDevice device = new KioskDevice("S-001", false);
Device inspectedDevice = device.withInspected(true);
assertNotSame(inspectedDevice, device);
assertFalse(device.isInspected());
assertTrue(inspectedDevice.isInspected());
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.lombok.with;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class StockWithUnitTest {
@Test
public void givenWithManuallyProvided_whenSkuChanged_thenManualMethodUsed() {
Stock stock = new Stock("sku-001", 5);
Stock modifiedStock = stock.withSku("sku-002");
Stock anotherModifiedStock = stock.withSKU("sku-003", "sku-004");
assertNotSame(modifiedStock, stock);
assertNotSame(anotherModifiedStock, stock);
assertTrue(modifiedStock.getSku().startsWith("mod"));
assertTrue(anotherModifiedStock.getSku().startsWith("mod"));
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.lombok.with;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UserWithUnitTest {
@Test
public void whenUserAuthenticated_thenClonedAndUpdated() {
User immutableUser = new User("testuser", "test@mail.com", false);
User authenticatedUser = immutableUser.withAuthenticated(true);
assertNotSame(immutableUser, authenticatedUser);
assertFalse(immutableUser.isAuthenticated());
assertTrue(authenticatedUser.isAuthenticated());
}
}

View File

@ -135,7 +135,8 @@
</build> </build>
<properties> <properties>
<exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass> <!-- <exec.mainClass>com.baeldung.micronaut.helloworld.server.ServerApplication</exec.mainClass> -->
<exec.mainClass>com.baeldung.micronaut.vs.springboot.CompareApplication</exec.mainClass>
<micronaut.version>1.0.0.RC2</micronaut.version> <micronaut.version>1.0.0.RC2</micronaut.version>
<jdk.version>1.8</jdk.version> <jdk.version>1.8</jdk.version>
<annotation.api.version>1.3.2</annotation.api.version> <annotation.api.version>1.3.2</annotation.api.version>

View File

@ -0,0 +1,9 @@
package com.baeldung.micronaut.vs.springboot;
import io.micronaut.runtime.Micronaut;
public class CompareApplication {
public static void main(String[] args) {
Micronaut.run(CompareApplication.class);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.micronaut.vs.springboot.client;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.annotation.Client;
@Client("/math")
public interface ArithmeticClient {
@Get("/sum/{number1}/{number2}")
String sum(float number1, float number2);
@Get("/subtract/{number1}/{number2}")
String subtract(float number1, float number2);
@Get("/multiply/{number1}/{number2}")
String multiply(float number1, float number2);
@Get("/divide/{number1}/{number2}")
String divide(float number1, float number2);
@Get("/memory")
String memory();
}

View File

@ -0,0 +1,41 @@
package com.baeldung.micronaut.vs.springboot.client;
import javax.inject.Singleton;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.http.client.annotation.Client;
@Singleton
public class ArithmeticClientImpl {
private RxHttpClient httpClient;
public ArithmeticClientImpl(@Client("/") RxHttpClient httpClient) {
this.httpClient = httpClient;
}
public String sum(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/sum/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
public String subtract(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/subtract/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
public String multiply(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/multiply/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
public String divide(float number1, float number2) {
HttpRequest<String> req = HttpRequest.GET("/math/divide/" + number1 + "/" + number2);
return httpClient.retrieve(req).blockingFirst();
}
public String memory() {
HttpRequest<String> req = HttpRequest.GET("/math/memory");
return httpClient.retrieve(req).blockingFirst();
}
}

View File

@ -0,0 +1,58 @@
package com.baeldung.micronaut.vs.springboot.controller;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import javax.inject.Inject;
import com.baeldung.micronaut.vs.springboot.service.ArithmeticService;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/math")
public class ArithmeticController {
@Inject
private ArithmeticService arithmeticService;
@Get("/sum/{number1}/{number2}")
public float getSum(float number1, float number2) {
return arithmeticService.add(number1, number2);
}
@Get("/subtract/{number1}/{number2}")
public float getDifference(float number1, float number2) {
return arithmeticService.subtract(number1, number2);
}
@Get("/multiply/{number1}/{number2}")
public float getMultiplication(float number1, float number2) {
return arithmeticService.multiply(number1, number2);
}
@Get("/divide/{number1}/{number2}")
public float getDivision(float number1, float number2) {
return arithmeticService.divide(number1, number2);
}
@Get("/memory")
public String getMemoryStatus() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
String memoryStats = "";
String init = String.format("Initial: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getInit() /1073741824);
String usedHeap = String.format("Used: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824);
String maxHeap = String.format("Max: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getMax() /1073741824);
String committed = String.format("Committed: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getCommitted() /1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.micronaut.vs.springboot.service;
import javax.inject.Singleton;
@Singleton
public class ArithmeticService {
public float add(float number1, float number2) {
return number1 + number2;
}
public float subtract(float number1, float number2) {
return number1 - number2;
}
public float multiply(float number1, float number2) {
return number1 * number2;
}
public float divide(float number1, float number2) {
if (number2 == 0) {
throw new IllegalArgumentException("'number2' cannot be zero");
}
return number1 / number2;
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.micronaut.vs.springboot;
import static org.junit.Assert.assertEquals;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import io.micronaut.context.ApplicationContext;
import io.micronaut.runtime.server.EmbeddedServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.micronaut.vs.springboot.client.ArithmeticClientImpl;
public class ArithmeticClientUnitTest {
private EmbeddedServer server;
private ArithmeticClientImpl client;
@Before
public void setup() {
server = ApplicationContext.run(EmbeddedServer.class);
client = server.getApplicationContext().getBean(ArithmeticClientImpl.class);
}
@After
public void cleanup() {
server.stop();
}
@Test
public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() {
String expected = Float.valueOf(10 + 20).toString();
assertEquals(expected, client.sum(10, 20));
}
@Test
public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() {
String expected = Float.valueOf(20 - 10).toString();
assertEquals(expected, client.subtract(20, 10));
}
@Test
public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() {
String expected = Float.valueOf(10 * 20).toString();
assertEquals(expected, client.multiply(10, 20));
}
@Test
public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() {
String expected = Float.valueOf(30 / 10).toString();
assertEquals(expected, client.divide(30, 10));
}
@Test
public void whenMemory_thenCorrectAnswerReturned() {
String expected = "Initial:";
assertThat(client.memory(), containsString(expected));
}
}

View File

@ -0,0 +1 @@
spring.mongodb.embedded.version=3.5.5

View File

@ -30,10 +30,6 @@
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
</dependency>
<dependency> <dependency>
<groupId>javax.transaction</groupId> <groupId>javax.transaction</groupId>
<artifactId>jta</artifactId> <artifactId>jta</artifactId>
@ -56,12 +52,10 @@
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId> <artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.hibernate</groupId> <groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId> <artifactId>hibernate-envers</artifactId>
<version>${hibernate.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
@ -84,8 +78,6 @@
<tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version> <tomcat-dbcp.version>9.0.0.M26</tomcat-dbcp.version>
<jta.version>1.1</jta.version> <jta.version>1.1</jta.version>
<guava.version>21.0</guava.version> <guava.version>21.0</guava.version>
<!-- persistence -->
<hibernate.version>5.2.10.Final</hibernate.version>
</properties> </properties>
</project> </project>

View File

@ -70,6 +70,7 @@
<module>spring-boot-swagger</module> <module>spring-boot-swagger</module>
<module>spring-boot-swagger-jwt</module> <module>spring-boot-swagger-jwt</module>
<module>spring-boot-testing</module> <module>spring-boot-testing</module>
<module>spring-boot-testing-2</module>
<module>spring-boot-vue</module> <module>spring-boot-vue</module>
<module>spring-boot-actuator</module> <module>spring-boot-actuator</module>
<module>spring-boot-data-2</module> <module>spring-boot-data-2</module>

View File

@ -5,4 +5,5 @@ This module contains articles about Spring Boot annotations
### Relevant Articles: ### Relevant Articles:
- [Spring Conditional Annotations](https://www.baeldung.com/spring-conditional-annotations) - [Spring Conditional Annotations](https://www.baeldung.com/spring-conditional-annotations)
- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation)
- More articles: [[<-- prev]](/spring-boot-modules/spring-boot-annotations) - More articles: [[<-- prev]](/spring-boot-modules/spring-boot-annotations)

View File

@ -0,0 +1 @@
spring.main.web-application-type=none

View File

@ -0,0 +1,15 @@
package com.baeldung.springbootconfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringContextTest {
@Test
public void contextLoads() {
}
}

View File

@ -9,5 +9,4 @@ This module contains articles about bootstrapping Spring Boot applications.
- [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine) - [Deploy a Spring Boot Application to Google App Engine](https://www.baeldung.com/spring-boot-google-app-engine)
- [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift) - [Deploy a Spring Boot Application to OpenShift](https://www.baeldung.com/spring-boot-deploy-openshift)
- [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk) - [Deploy a Spring Boot Application to AWS Beanstalk](https://www.baeldung.com/spring-boot-deploy-aws-beanstalk)
- [Guide to @SpringBootConfiguration in Spring Boot](https://www.baeldung.com/springbootconfiguration-annotation)
- [Implement Health Checks in OpenShift](https://www.baeldung.com/ops/openshift-health-checks) - [Implement Health Checks in OpenShift](https://www.baeldung.com/ops/openshift-health-checks)

View File

@ -1,6 +1,7 @@
package com.baeldung.prefix; package com.baeldung.prefix;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -8,12 +9,12 @@ import org.springframework.web.bind.annotation.GetMapping;
@Controller @Controller
public class PrefixController { public class PrefixController {
@Value(value = "${server.port}") @Autowired
private int serverPort; private Environment environment;
@GetMapping("/prefix") @GetMapping("/prefix")
public String getServerPortInfo(final Model model) { public String getServerPortInfo(final Model model) {
model.addAttribute("serverPort", serverPort); model.addAttribute("serverPort", environment.getProperty("server.port"));
return "prefix"; return "prefix";
} }
} }

View File

@ -1,15 +1,11 @@
package com.baeldung; package com.baeldung;
import com.baeldung.jobrunr.service.SampleJobService; import com.baeldung.jobrunr.service.SampleJobService;
import org.jobrunr.jobs.mappers.JobMapper;
import org.jobrunr.scheduling.JobScheduler; import org.jobrunr.scheduling.JobScheduler;
import org.jobrunr.scheduling.cron.Cron; import org.jobrunr.scheduling.cron.Cron;
import org.jobrunr.storage.InMemoryStorageProvider;
import org.jobrunr.storage.StorageProvider;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@ -23,13 +19,6 @@ public class JobRunrSpringBootApp {
SpringApplication.run(JobRunrSpringBootApp.class, args); SpringApplication.run(JobRunrSpringBootApp.class, args);
} }
@Bean
public StorageProvider storageProvider(JobMapper jobMapper) {
InMemoryStorageProvider storageProvider = new InMemoryStorageProvider();
storageProvider.setJobMapper(jobMapper);
return storageProvider;
}
@PostConstruct @PostConstruct
public void scheduleRecurrently() { public void scheduleRecurrently() {
jobScheduler.<SampleJobService>scheduleRecurrently(Cron.every5minutes(), x -> x.executeSampleJob("a recurring job")); jobScheduler.<SampleJobService>scheduleRecurrently(Cron.every5minutes(), x -> x.executeSampleJob("a recurring job"));

View File

@ -0,0 +1,18 @@
package com.baeldung.config;
import org.jobrunr.jobs.mappers.JobMapper;
import org.jobrunr.storage.InMemoryStorageProvider;
import org.jobrunr.storage.StorageProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class StorageProviderConfig {
@Bean
public StorageProvider storageProvider(JobMapper jobMapper) {
InMemoryStorageProvider storageProvider = new InMemoryStorageProvider();
storageProvider.setJobMapper(jobMapper);
return storageProvider;
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.micronaut.vs.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan("com.baeldung.micronaut.vs.springboot")
public class CompareApplication {
public static void main(final String[] args) {
SpringApplication.run(CompareApplication.class, args);
}
}

View File

@ -0,0 +1,60 @@
package com.baeldung.micronaut.vs.springboot.controller;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.micronaut.vs.springboot.service.ArithmeticService;
@RestController
@RequestMapping("/math")
public class ArithmeticController {
@Autowired
private ArithmeticService arithmeticService;
@GetMapping("/sum/{number1}/{number2}")
public float getSum(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.add(number1, number2);
}
@GetMapping("/subtract/{number1}/{number2}")
public float getDifference(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.subtract(number1, number2);
}
@GetMapping("/multiply/{number1}/{number2}")
public float getMultiplication(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.multiply(number1, number2);
}
@GetMapping("/divide/{number1}/{number2}")
public float getDivision(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.divide(number1, number2);
}
@GetMapping("/memory")
public String getMemoryStatus() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
String memoryStats = "";
String init = String.format("Initial: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getInit() /1073741824);
String usedHeap = String.format("Used: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824);
String maxHeap = String.format("Max: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getMax() /1073741824);
String committed = String.format("Committed: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getCommitted() /1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.micronaut.vs.springboot.service;
import org.springframework.stereotype.Service;
@Service
public class ArithmeticService {
public float add(float number1, float number2) {
return number1 + number2;
}
public float subtract(float number1, float number2) {
return number1 - number2;
}
public float multiply(float number1, float number2) {
return number1 * number2;
}
public float divide(float number1, float number2) {
if (number2 == 0) {
throw new IllegalArgumentException("'number2' cannot be zero");
}
return number1 / number2;
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.micronaut.vs.springboot.controller;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.hamcrest.Matchers.containsString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.baeldung.micronaut.vs.springboot.CompareApplication;
@SpringBootTest(classes = CompareApplication.class)
@AutoConfigureMockMvc
public class ArithmeticControllerUnitTest {
@Autowired
private MockMvc mockMvc;
@Test
public void givenTwoNumbers_whenAdd_thenCorrectAnswerReturned() throws Exception {
Float expected = Float.valueOf(10 + 20);
this.mockMvc.perform(MockMvcRequestBuilders.get("/math/sum/10/20")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(expected.toString()));
}
@Test
public void givenTwoNumbers_whenSubtract_thenCorrectAnswerReturned() throws Exception {
Float expected = Float.valueOf(20 - 10);
this.mockMvc.perform(MockMvcRequestBuilders.get("/math/subtract/20/10")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(expected.toString()));
}
@Test
public void givenTwoNumbers_whenMultiply_thenCorrectAnswerReturned() throws Exception {
Float expected = Float.valueOf(20 * 10);
this.mockMvc.perform(MockMvcRequestBuilders.get("/math/multiply/20/10")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(expected.toString()));
}
@Test
public void givenTwoNumbers_whenDivide_thenCorrectAnswerReturned() throws Exception {
Float expected = Float.valueOf(20 / 10);
this.mockMvc.perform(MockMvcRequestBuilders.get("/math/divide/20/10")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(expected.toString()));
}
@Test
public void whenMemory_thenMemoryStringReturned() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/math/memory")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Initial:")));
}
}

View File

@ -95,7 +95,7 @@
<jpa.version>2.2</jpa.version> <jpa.version>2.2</jpa.version>
<guava.version>18.0</guava.version> <guava.version>18.0</guava.version>
<subethasmtp.version>3.1.7</subethasmtp.version> <subethasmtp.version>3.1.7</subethasmtp.version>
<springcloud.version>3.0.2</springcloud.version> <springcloud.version>3.1.0</springcloud.version>
<httpclient.version>4.5.8</httpclient.version> <httpclient.version>4.5.8</httpclient.version>
</properties> </properties>

View File

@ -0,0 +1,5 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,12 @@
## Spring Boot Testing
This module contains articles about Spring Boot testing
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level)
- More articles: [[<-- prev]](../spring-boot-testing)

View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-testing-2</artifactId>
<name>spring-boot-testing-2</name>
<packaging>jar</packaging>
<description>This is simple boot application for demonstrating testing features.</description>
<parent>
<groupId>com.baeldung.spring-boot-modules</groupId>
<artifactId>spring-boot-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<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>
<properties>
<start-class>com.baeldung.boot.Application</start-class>
</properties>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.boot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,3 @@
# logging.level.com.baeldung.testloglevel=DEBUG
# logging.level.root=INFO

View File

@ -0,0 +1,13 @@
<configuration>
<include resource="/org/springframework/boot/logging/logback/base.xml"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="error">
<appender-ref ref="STDOUT"/>
</root>
<logger name="com.baeldung.testloglevel" level="debug"/>
</configuration>

View File

@ -10,9 +10,9 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing) - [Testing with Spring and Spock](https://www.baeldung.com/spring-spock-testing)
- [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test) - [Exclude Auto-Configuration Classes in Spring Boot Tests](https://www.baeldung.com/spring-boot-exclude-auto-configuration-test)
- [Setting the Log Level in Spring Boot when Testing](https://www.baeldung.com/spring-boot-testing-log-level)
- [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis) - [Embedded Redis Server with Spring Boot Test](https://www.baeldung.com/spring-embedded-redis)
- [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties) - [Testing Spring Boot @ConfigurationProperties](https://www.baeldung.com/spring-boot-testing-configurationproperties)
- [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution) - [Prevent ApplicationRunner or CommandLineRunner Beans From Executing During Junit Testing](https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution)
- [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing) - [Testing in Spring Boot](https://www.baeldung.com/spring-boot-testing)
- [Fixing the NoSuchMethodError JUnit Error](https://www.baeldung.com/junit-nosuchmethoderror) - [Fixing the NoSuchMethodError JUnit Error](https://www.baeldung.com/junit-nosuchmethoderror)
- More articles: [[more -->]](../spring-boot-testing-2)

View File

@ -9,5 +9,4 @@
<root level="error"> <root level="error">
<appender-ref ref="STDOUT"/> <appender-ref ref="STDOUT"/>
</root> </root>
<logger name="com.baeldung.testloglevel" level="debug"/>
</configuration> </configuration>

View File

@ -42,6 +42,8 @@
<properties> <properties>
<rate.limit.version>2.2.0.RELEASE</rate.limit.version> <rate.limit.version>2.2.0.RELEASE</rate.limit.version>
<spring-boot.version>2.4.7</spring-boot.version>
<spring-cloud-dependencies.version>2020.0.4</spring-cloud-dependencies.version>
</properties> </properties>
</project> </project>

View File

@ -0,0 +1,15 @@
package com.baeldung.springsecuritythymeleaf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -8,6 +8,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration @Configuration
@ -32,19 +33,15 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
} }
@Autowired @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
auth.inMemoryAuthentication() auth.inMemoryAuthentication()
.withUser("user") .withUser("user")
.password(passwordEncoder().encode("password")) .password(passwordEncoder.encode("password"))
.roles("USER") .roles("USER")
.and() .and()
.withUser("admin") .withUser("admin")
.password(passwordEncoder().encode("admin")) .password(passwordEncoder.encode("admin"))
.roles("ADMIN"); .roles("ADMIN");
} }
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} }

View File

@ -9,11 +9,13 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@WebMvcTest @WebMvcTest
@Import(PasswordEncoderConfiguration.class)
public class ViewControllerIntegrationTest { public class ViewControllerIntegrationTest {
@Autowired @Autowired

View File

@ -0,0 +1,15 @@
package com.baeldung.spring.session;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -15,8 +15,8 @@ import org.springframework.security.crypto.password.PasswordEncoder;
public class SecurityConfig extends WebSecurityConfigurerAdapter { public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder.encode("password")).roles("ADMIN");
} }
@Override @Override
@ -24,8 +24,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated(); http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated();
} }
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} }

View File

@ -30,6 +30,7 @@
<module>spring-mvc-views</module> <module>spring-mvc-views</module>
<module>spring-mvc-webflow</module> <module>spring-mvc-webflow</module>
<module>spring-mvc-xml</module> <module>spring-mvc-xml</module>
<module>spring-mvc-xml-2</module>
<module>spring-rest-angular</module> <module>spring-rest-angular</module>
<module>spring-rest-http</module> <module>spring-rest-http</module>
<module>spring-rest-http-2</module> <module>spring-rest-http-2</module>

View File

@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -0,0 +1,14 @@
## Spring MVC XML
This module contains articles about Spring MVC with XML configuration
### The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
- [Exploring SpringMVCs Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags)
- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable)
- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error)
- More articles: [[<-- prev]](../spring-mvc-xml)

View File

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-mvc-xml-2</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-mvc-xml-2</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-web-modules</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- Json conversion -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring-boot.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<spring-boot.version>1.5.10.RELEASE</spring-boot.version>
<mysql-connector-java.version>5.1.40</mysql-connector-java.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<hibernate-validator.version>6.0.10.Final</hibernate-validator.version>
<javax.el.version>3.0.1-b08</javax.el.version>
<guava.version>19.0</guava.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ImportResource("classpath:webMvcConfig.xml")
@Configuration
@ComponentScan
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {
super();
}
}

View File

@ -6,6 +6,7 @@ import java.util.ResourceBundle;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.MessageSourceResourceBundle; import org.springframework.context.support.MessageSourceResourceBundle;
import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

View File

@ -0,0 +1,16 @@
package com.baeldung.spring.nomapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class GreetingController {
@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String get(ModelMap model) {
model.addAttribute("message", "Hello, World!");
return "greeting";
}
}

View File

@ -1,12 +1,17 @@
package com.baeldung.spring.controller; package com.baeldung.spring.paramsvalidation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.*; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@Controller @Controller
@RequestMapping("/public/api/1") @RequestMapping("/public/api/1")

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.form; package com.baeldung.spring.taglibrary;
import java.util.List; import java.util.List;

View File

@ -1,14 +1,5 @@
package com.baeldung.spring.controller; package com.baeldung.spring.taglibrary;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import com.baeldung.spring.form.Person;
import com.baeldung.spring.validator.PersonValidator;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
@ -19,6 +10,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@Controller @Controller
public class PersonController { public class PersonController {

View File

@ -1,6 +1,5 @@
package com.baeldung.spring.validator; package com.baeldung.spring.taglibrary;
import com.baeldung.spring.form.Person;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils; import org.springframework.validation.ValidationUtils;

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,3 @@
required.name = Name is required!
NotEmpty.person.password = Password is required!

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>image/jpeg</value>
<value>image/png</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.baeldung.spring"/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:view-controller path="/sample.html" view-name="sample"/>
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="messages" />
</bean>
<bean id="validationProcessor" class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor" />
</beans>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.baeldung.spring"/>
</beans>

View File

@ -0,0 +1,9 @@
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>

View File

@ -0,0 +1,7 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
>
<display-name>Spring MVC XML Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- additional config -->
<session-config>
<session-timeout>10</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<location>/errors</location>
</error-page>
</web-app>

View File

@ -0,0 +1,15 @@
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Examples</title>
</head>
<body>
<h1>Spring MVC Examples</h1>
</body>
</html>

View File

@ -0,0 +1,19 @@
package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.baeldung.spring.ClientWebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ClientWebConfig.class)
@WebAppConfiguration
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,5 +1,6 @@
package com.baeldung.spring.controller; package com.baeldung.spring.paramsvalidation;
import com.baeldung.spring.ClientWebConfigJava;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -11,9 +12,6 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.ClientWebConfig;
import com.baeldung.spring.ClientWebConfigJava;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

View File

@ -12,12 +12,10 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Returning Image/Media Data with Spring MVC](https://www.baeldung.com/spring-mvc-image-media-data) - [Returning Image/Media Data with Spring MVC](https://www.baeldung.com/spring-mvc-image-media-data)
- [Geolocation by IP in Java](https://www.baeldung.com/geolocation-by-ip-with-maxmind) - [Geolocation by IP in Java](https://www.baeldung.com/geolocation-by-ip-with-maxmind)
- [Guide to JavaServer Pages (JSP)](https://www.baeldung.com/jsp) - [Guide to JavaServer Pages (JSP)](https://www.baeldung.com/jsp)
- [Exploring SpringMVCs Form Tag Library](https://www.baeldung.com/spring-mvc-form-tags)
- [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config)
- [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml)
- [Validating RequestParams and PathVariables in Spring](https://www.baeldung.com/spring-validate-requestparam-pathvariable)
- [Debugging the Spring MVC 404 “No mapping found for HTTP request” Error](https://www.baeldung.com/spring-mvc-404-error)
- [Introduction to Servlets and Servlet Containers](https://www.baeldung.com/java-servlets-containers-intro) - [Introduction to Servlets and Servlet Containers](https://www.baeldung.com/java-servlets-containers-intro)
- More articles: [[more -->]](../spring-mvc-xml-2)
## Spring MVC with XML Configuration Example Project ## Spring MVC with XML Configuration Example Project

View File

@ -39,11 +39,6 @@
<version>${jstl.version}</version> <version>${jstl.version}</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- Json conversion --> <!-- Json conversion -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>