2022-05 spring-06-avdanced-config added

This commit is contained in:
stvort
2022-06-14 18:20:56 +04:00
parent abad2f4bbe
commit 7f812541be
95 changed files with 1807 additions and 0 deletions
@@ -0,0 +1,4 @@
.idea/
*.iml
target/
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,2 @@
# application-events-demo
Пример работы с событиями
@@ -0,0 +1,62 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>application-events-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>application-events-demo</name>
<description>Application events demo</description>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<spring.shell.version>2.0.1.RELEASE</spring.shell.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.shell</groupId>
<artifactId>spring-shell-starter</artifactId>
<version>${spring.shell.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,26 @@
package ru.otus.example.applicationeventsdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
@SpringBootApplication
public class ApplicationEventsDemoApplication {
//@Bean @Primary
//@Bean(name = "applicationEventMulticaster")
public ApplicationEventMulticaster applicationEventMulticaster() {
SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
return eventMulticaster;
}
public static void main(String[] args) {
SpringApplication.run(ApplicationEventsDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.applicationeventsdemo.events;
public interface EventsPublisher {
void publish();
}
@@ -0,0 +1,15 @@
package ru.otus.example.applicationeventsdemo.events;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
public class HalfAGlassOfWaterEvent extends ApplicationEvent {
@Getter
private final String payload;
public HalfAGlassOfWaterEvent(Object source) {
super(source);
payload = "Осталось половина стакана воды!!!";
}
}
@@ -0,0 +1,17 @@
package ru.otus.example.applicationeventsdemo.events;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class HalfAGlassOfWaterEventPublisher implements EventsPublisher {
private final ApplicationEventPublisher publisher;
@Override
public void publish() {
publisher.publishEvent(new HalfAGlassOfWaterEvent(this));
}
}
@@ -0,0 +1,18 @@
package ru.otus.example.applicationeventsdemo.events;
import lombok.SneakyThrows;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class NegativeRespondent implements ApplicationListener<HalfAGlassOfWaterEvent> {
@SneakyThrows
@Override
public void onApplicationEvent(HalfAGlassOfWaterEvent halfAGlassOfWaterEvent) {
Thread.sleep(100);
System.out.println("Негативно настроенный слушатель");
System.out.println(String.format("- %s", halfAGlassOfWaterEvent.getPayload()));
System.out.println("- Какой ужас. Теперь он наполовину пуст!!!\n\n");
}
}
@@ -0,0 +1,18 @@
package ru.otus.example.applicationeventsdemo.events;
import lombok.SneakyThrows;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class PositiveRespondent {
@SneakyThrows
@EventListener
public void onApplicationEvent(HalfAGlassOfWaterEvent halfAGlassOfWaterEvent) {
Thread.sleep(100);
System.out.println("Позитивно настроенный слушатель");
System.out.println(String.format("- %s", halfAGlassOfWaterEvent.getPayload()));
System.out.println("- Ничего. Главное, что он наполовину полон!!!\n\n");
}
}
@@ -0,0 +1,35 @@
package ru.otus.example.applicationeventsdemo.shell;
import lombok.RequiredArgsConstructor;
import org.springframework.shell.Availability;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellMethodAvailability;
import org.springframework.shell.standard.ShellOption;
import ru.otus.example.applicationeventsdemo.events.EventsPublisher;
@ShellComponent
@RequiredArgsConstructor
public class ApplicationEventsCommands {
private final EventsPublisher eventsPublisher;
private String userName;
@ShellMethod(value = "Login command", key = {"l", "login"})
public String login(@ShellOption(defaultValue = "AnyUser") String userName) {
this.userName = userName;
return String.format("Добро пожаловать: %s", userName);
}
@ShellMethod(value = "Publish event command", key = {"p", "pub", "publish"})
@ShellMethodAvailability(value = "isPublishEventCommandAvailable")
public String publishEvent() {
eventsPublisher.publish();
return "Событие опубликовано";
}
private Availability isPublishEventCommandAvailable() {
return userName == null? Availability.unavailable("Сначала залогиньтесь"): Availability.available();
}
}
@@ -0,0 +1,8 @@
logging:
level:
root: ERROR
spring:
main:
allow-circular-references: true
@@ -0,0 +1,67 @@
package ru.otus.example.applicationeventsdemo.shell;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.shell.Availability;
import org.springframework.shell.CommandNotCurrentlyAvailable;
import org.springframework.shell.Shell;
import org.springframework.test.annotation.DirtiesContext;
import ru.otus.example.applicationeventsdemo.events.EventsPublisher;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@DisplayName("Тест команд shell ")
@SpringBootTest
class ApplicationEventsCommandsTest {
@MockBean
private EventsPublisher eventsPublisher;
@Autowired
private Shell shell;
private static final String GREETING_PATTERN = "Добро пожаловать: %s";
private static final String DEFAULT_LOGIN = "AnyUser";
private static final String CUSTOM_LOGIN = "Вася";
private static final String COMMAND_LOGIN = "login";
private static final String COMMAND_LOGIN_SHORT = "l";
private static final String COMMAND_PUBLISH = "publish";
private static final String COMMAND_PUBLISH_EXPECTED_RESULT = "Событие опубликовано";
private static final String COMMAND_LOGIN_PATTERN = "%s %s";
@DisplayName(" должен возвращать приветствие для всех форм команды логина")
@Test
void shouldReturnExpectedGreetingAfterLoginCommandEvaluated() {
String res = (String) shell.evaluate(() -> COMMAND_LOGIN);
assertThat(res).isEqualTo(String.format(GREETING_PATTERN, DEFAULT_LOGIN));
res = (String) shell.evaluate(() -> COMMAND_LOGIN_SHORT);
assertThat(res).isEqualTo(String.format(GREETING_PATTERN, DEFAULT_LOGIN));
res = (String) shell.evaluate(() -> String.format(COMMAND_LOGIN_PATTERN, COMMAND_LOGIN_SHORT, CUSTOM_LOGIN));
assertThat(res).isEqualTo(String.format(GREETING_PATTERN, CUSTOM_LOGIN));
}
@DisplayName(" должен возвращать CommandNotCurrentlyAvailable если при попытке выполнения команды publish пользователь выполнил вход")
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
@Test
void shouldReturnCommandNotCurrentlyAvailableObjectWhenUserDoesNotLoginAfterPublishCommandEvaluated() {
Object res = shell.evaluate(() -> COMMAND_PUBLISH);
assertThat(res).isInstanceOf(CommandNotCurrentlyAvailable.class);
}
@DisplayName(" должен возвращать статус выполнения команды publish и вызвать соответствующий метод сервиса есл икоманда выполнена после входа")
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
@Test
void shouldReturnExpectedMessageAndFirePublishMethodAfterPublishCommandEvaluated() {
shell.evaluate(() -> COMMAND_LOGIN);
String res = (String) shell.evaluate(() -> COMMAND_PUBLISH);
assertThat(res).isEqualTo(COMMAND_PUBLISH_EXPECTED_RESULT);
verify(eventsPublisher, times(1)).publish();
}
}
@@ -0,0 +1,6 @@
spring:
shell:
interactive:
enabled: false
main:
allow-circular-references: true
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,11 @@
#### Упражнение №1
Условия вечеринки:
- Алексей придет если condition.alexey-exists=true
- Анна придет если будет Алексей
- Олег придет если включен профиль Oleg
- Петр придет если включен профиль Peter
- Янис придет если condition.yanis-exists=true
- Яна придет если нет Алексея, но есть Янис
Измените только одну настройку в application.yml, чтобы на вечеринку пришло максимальное количество людей
Напечатать имена пришедших на вечеринку можно с помощью команды "ppm" или "print-party-members"
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>conditional-and-profiles-exercise</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,17 @@
package ru.otus.example.conditionalandprofilesdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import ru.otus.example.conditionalandprofilesdemo.model.Party;
@SpringBootApplication
public class ConditionalAndProfilesDemoApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(ConditionalAndProfilesDemoApplication.class, args);
Party party = ctx.getBean(Party.class);
party.printPartyMembers();
}
}
@@ -0,0 +1,14 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
@ConditionalOnProperty(name = "condition.alexey-exists", havingValue = "true")
@Component
public class Alexey extends Friend {
@Override
public String getName() {
return "Алексей";
}
}
@@ -0,0 +1,14 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
@ConditionalOnBean(Alexey.class)
@Component
public class Anna extends Friend {
@Override
public String getName() {
return "Аня";
}
}
@@ -0,0 +1,14 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
@Profile("Oleg")
@Component
public class Oleg extends Friend {
@Override
public String getName() {
return "Олег";
}
}
@@ -0,0 +1,19 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
import java.util.List;
import java.util.stream.Collectors;
@Component
@RequiredArgsConstructor
public class Party {
private final List<Friend> partyMembers;
public void printPartyMembers() {
System.out.println("Участники вечеринки:");
System.out.println(partyMembers.stream().map(Friend::getName).collect(Collectors.joining("\n")));
}
}
@@ -0,0 +1,15 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
@Profile("Peter")
@Component
public class Peter extends Friend {
@Override
public String getName() {
return "Петр";
}
}
@@ -0,0 +1,16 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
import ru.otus.example.conditionalandprofilesdemo.model.conditions.YanaConditions;
@Conditional(YanaConditions.class)
@Component
public class Yana extends Friend {
@Override
public String getName() {
return "Яна";
}
}
@@ -0,0 +1,14 @@
package ru.otus.example.conditionalandprofilesdemo.model;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import ru.otus.example.conditionalandprofilesdemo.model.base.Friend;
@ConditionalOnProperty(name = "condition.yanis-exists", havingValue = "true")
@Component
public class Yanis extends Friend {
@Override
public String getName() {
return "Янис";
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.conditionalandprofilesdemo.model.base;
public abstract class Friend {
public abstract String getName();
}
@@ -0,0 +1,20 @@
package ru.otus.example.conditionalandprofilesdemo.model.conditions;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
public class YanaConditions extends AllNestedConditions {
public YanaConditions() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = "condition.alexey-exists", havingValue = "false")
static class AlexeyDoesNotExistsCondition {
}
@ConditionalOnProperty(name = "condition.yanis-exists", havingValue = "true")
static class YanisExistsCondition {
}
}
@@ -0,0 +1,2 @@
condition:
#yanis-exists: true
@@ -0,0 +1,20 @@
condition:
alexey-exists: true
yanis-exists: false
spring:
profiles:
#Доступные профили: Oleg и Peter
active:
logging:
level:
root: ERROR
---
spring:
profiles: Peter
condition:
yanis-exists: true
+23
View File
@@ -0,0 +1,23 @@
<?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>
<groupId>ru.otus</groupId>
<artifactId>advanced-config-class-work</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<modules>
<module>conditional-and-profiles-exercise</module>
<module>application-events-demo</module>
<module>test-configuration-exercise-1</module>
<module>test-configuration-exercise-2</module>
<module>test-configuration-exercise-3</module>
<module>test-configuration-solution-1</module>
<module>test-configuration-solution-2</module>
<module>test-configuration-solution-3</module>
</modules>
</project>
@@ -0,0 +1,9 @@
1638867120546:p
1638867124184:l
1638867125867:p
1638867146689:l
1638867147641:p
1655216108320:l
1655216109269:p
1655216123518:l
1655216124571:p
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,9 @@
#### Упражнение №2. Должен остаться только один
С помощью вложенных конфигураций сделать так,
чтобы прошел NestedConfigurationDemoTest
(family должно содержать только собаку)
- Сделать вложенный класс конфигурации. Не забываем про static
- Выбрать тип конфигурации (@Configuration/@TestConfiguration)
- С помощью @Bean/@ComponentScan добавить в контекст нужный бин(ы)
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-exercise-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В NestedConfigurationDemoTest семья должна ")
@SpringBootTest
public class NestedConfigurationDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать только собаку ")
@Test
void shouldContainOnlyDog() {
assertThat(family).containsOnlyKeys("dog");
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В PlainSpringBootTestDemoTest семья должна ")
@SpringBootTest
public class PlainSpringBootTestDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, сына и собаку ")
@Test
void shouldContainAllFamilyExceptFather() {
assertThat(family).containsOnlyKeys("mother", "son", "dog");
}
}
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,9 @@
#### Упражнение №3. Вернуть отца в семью
С помощью вложенных конфигураций сделать так,
чтобы прошел NestedTestConfigurationDemoTest
(family должно содержать маму, папу, сына и собаку)
- Сделать вложенный класс конфигурации. Не забываем про static
- Выбрать тип конфигурации (@Configuration/@TestConfiguration)
- С помощью @Bean/@ComponentScan добавить в контекст нужный бин(ы)
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-exercise-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В NestedTestConfigurationDemoTest семья должна ")
@SpringBootTest
public class NestedTestConfigurationDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, папу, сына и собаку ")
@Test
void shouldContainAllFamilyWithFather() {
assertThat(family).containsOnlyKeys("mother", "father", "son", "dog");
}
}
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,8 @@
#### Упражнение №4. Вся семья, но без собаки
С помощью внешней конфигурации сделать так,
чтобы прошел SpringBootTestWithExternalLimitationDemoTest
(family должно содержать маму, папу и сына)
- Над TestSpringBootConfiguration повесить @SpringBootConfiguration
- С помощью @Bean/@ComponentScan добавить в контекст нужный бин(ы)
@@ -0,0 +1,51 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-exercise-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>test-configuration-demo</name>
<description>Test configuration demo</description>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В SpringBootTestWithExternalLimitationDemoTest семья должна ")
@SpringBootTest
public class SpringBootTestWithExternalLimitationDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, папу и сына")
@Test
void shouldContainAllFamilyExceptFather() {
assertThat(family).containsOnlyKeys("mother", "father", "son");
}
}
@@ -0,0 +1,4 @@
package ru.otus.example.testconfigurationdemo.demo;
public class TestSpringBootConfiguration {
}
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,7 @@
#### Решение упражнения №2
По заданию нужно ограничить контекст одним бином с помощью вложенной конфигурации.
@TestConfiguration не ограничивает, а дополняет контекст новыми бинами или подменяет те, что уже там.
Соответственно выбираем @Configuration. Вешаем его над вложенным статическим классом.
Т.к. Dog является @Component, то для его размещения в контексте подойдет любое из:
- @ComponentScan("ru.otus.example.testconfigurationdemo.family.pets") над конфигурацией
- Создание бина, через метод с аннотацией @Bean внутри конфигурации
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-solution-1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,41 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import ru.otus.example.testconfigurationdemo.family.pets.Dog;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В NestedConfigurationDemoTest семья должна ")
@SpringBootTest
public class NestedConfigurationDemoTest {
@ComponentScan("ru.otus.example.testconfigurationdemo.family.pets")
@Configuration
static class NestedConfiguration {
/*
@Bean
FamilyMember dog() {
return new Dog();
}
*/
}
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать только собаку ")
@Test
void shouldContainOnlyDog() {
assertThat(family).containsOnlyKeys("dog");
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В PlainSpringBootTestDemoTest семья должна ")
@SpringBootTest
public class PlainSpringBootTestDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, сына и собаку ")
@Test
void shouldContainAllFamilyExceptFather() {
assertThat(family).containsOnlyKeys("mother", "son", "dog");
}
}
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,8 @@
#### Решение упражнения №3
По заданию нужно добавить в контекст бин, которого там нет, с помощью вложенной конфигурации.
Эту проблему можно решить с помощью @Configuration, фактически заново сформировав контекст.
При этом @TestConfiguration может дополнить существующий. Соответственно выбираем его и вешаем над вложенным статическим классом.
Т.к. Father НЕ является @Component, то для его размещения в контексте нужно его создать,
через метод с аннотацией @Bean внутри тестовой конфигурации
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-solution-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,37 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import ru.otus.example.testconfigurationdemo.family.parents.Father;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В NestedTestConfigurationDemoTest семья должна ")
@SpringBootTest
public class NestedTestConfigurationDemoTest {
@TestConfiguration
static class NestedTestConfiguration {
@Bean
FamilyMember father() {
return new Father();
}
}
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, папу, сына и собаку ")
@Test
void shouldContainAllFamilyWithFather() {
assertThat(family).containsOnlyKeys("mother", "father", "son", "dog");
}
}
@@ -0,0 +1,32 @@
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
#other
*.bat
*/.idea
*.iml
*/target
.idea
*.iml
target
@@ -0,0 +1,12 @@
#### Решение упражнения №4
По заданию нужно ограничить контекст заданными бинами, с помощью внешней конфигурации.
Вешаем @SpringBootConfiguration над внешним классом TestSpringBootConfiguration.
Теперь сканирование конфигураций не уйдет далше него. Ни одного бина не найдется.
Значит нужно формировать контекст самим.
По заданию в нем должны быть бины типов Mother, Son и Father. Первые два являются @Component.
Их можно разместить в контексте просканировав соответствующие пакеты с помощью @ComponentScan
Т.к. Father НЕ является @Component, то для его размещения в контексте нужно его создать,
через метод с аннотацией @Bean внутри тестовой конфигурации
@@ -0,0 +1,49 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
<groupId>ru.otus.example</groupId>
<artifactId>test-configuration-solution-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package ru.otus.example.testconfigurationdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("ru.otus.example.testconfigurationdemo.family")
@SpringBootApplication
public class TestConfigurationDemoApplication {
public static void main(String[] args) {
SpringApplication.run(TestConfigurationDemoApplication.class, args);
}
}
@@ -0,0 +1,5 @@
package ru.otus.example.testconfigurationdemo.family;
public abstract class FamilyMember {
public abstract String getName();
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.childrens;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Son extends FamilyMember {
@Override
public String getName() {
return "Сын";
}
}
@@ -0,0 +1,10 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
public class Father extends FamilyMember {
@Override
public String getName() {
return "Папа";
}
}
@@ -0,0 +1,12 @@
package ru.otus.example.testconfigurationdemo.family.parents;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Mother extends FamilyMember {
@Override
public String getName() {
return "Мама";
}
}
@@ -0,0 +1,13 @@
package ru.otus.example.testconfigurationdemo.family.pets;
import org.springframework.stereotype.Component;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
@Component
public class Dog extends FamilyMember {
@Override
public String getName() {
return "Собака";
}
}
@@ -0,0 +1,26 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@DisplayName("В SpringBootTestWithExternalLimitationDemoTest семья должна ")
@SpringBootTest
public class SpringBootTestWithExternalLimitationDemoTest {
@Autowired
private Map<String, FamilyMember> family;
@DisplayName(" содержать маму, папу и сына")
@Test
void shouldContainAllFamilyExceptFather() {
assertThat(family).containsOnlyKeys("mother", "father", "son");
}
}
@@ -0,0 +1,17 @@
package ru.otus.example.testconfigurationdemo.demo;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import ru.otus.example.testconfigurationdemo.family.FamilyMember;
import ru.otus.example.testconfigurationdemo.family.parents.Father;
@ComponentScan({"ru.otus.example.testconfigurationdemo.family.parents",
"ru.otus.example.testconfigurationdemo.family.childrens"})
@SpringBootConfiguration
public class TestSpringBootConfiguration {
@Bean
FamilyMember father() {
return new Father();
}
}