mirror of
https://github.com/OtusTeam/Spring.git
synced 2026-05-30 10:50:42 +00:00
2025-05 spring-06-bean-scopes-and-lifecycle
This commit is contained in:
@@ -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,20 @@
|
||||
#### Упражнение №2
|
||||
|
||||
- Изучить классы ничего в них не меняя:
|
||||
- CustomBeanFactoryPostProcessor
|
||||
- CustomBeanPostProcessor
|
||||
- CustomLifeCycleBean
|
||||
- Запуститить приложение
|
||||
- Изучить распечатанный жизненный цикл
|
||||
|
||||
#### Упражнение №3
|
||||
|
||||
- В application.yml выставить spring.shell.interactive.enabled в true
|
||||
- Запуститить приложение командой "cfn" или "call-favorite-number"
|
||||
- Запомнить результат
|
||||
- В CustomBeanFactoryPostProcessor раскомментировать блок кода
|
||||
- Запуститить приложение командой "cfn" или "call-favorite-number"
|
||||
- Что изменилось?
|
||||
- В CustomBeanPostProcessor раскомментировать строку
|
||||
- Запуститить приложение командой "cfn" или "call-favorite-number"
|
||||
- Что изменилось теперь? Круто, да?
|
||||
@@ -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>3.4.2</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
<groupId>ru.otus.example</groupId>
|
||||
<artifactId>beans-lifecycle-exercise</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<snakeyaml.version>2.0</snakeyaml.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package ru.otus.example.beanslifecycledemo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import ru.otus.example.beanslifecycledemo.domain.Phone;
|
||||
|
||||
@SpringBootApplication
|
||||
public class BeansLifecycleDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ApplicationContext ctx = SpringApplication.run(BeansLifecycleDemoApplication.class, args);
|
||||
try {
|
||||
Phone phone = ctx.getBean(Phone.class);
|
||||
phone.callFavoriteNumber();
|
||||
} catch (Exception e) {
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package ru.otus.example.beanslifecycledemo.domain;
|
||||
|
||||
public class FriendPhoneNumber extends PhoneNumber {
|
||||
@Override
|
||||
public String getOwnerName() {
|
||||
return "Друг";
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package ru.otus.example.beanslifecycledemo.domain;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class GirlfiendPhoneNumber extends PhoneNumber {
|
||||
@Override
|
||||
public String getOwnerName() {
|
||||
return "Подруга";
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package ru.otus.example.beanslifecycledemo.domain;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "lifecycle.print.enabled", havingValue = "false")
|
||||
@RequiredArgsConstructor
|
||||
public class Phone {
|
||||
private final String greeting = "Погнали к родителям";
|
||||
|
||||
private final PhoneNumber favoriteNumber;
|
||||
|
||||
public void callFavoriteNumber() {
|
||||
System.out.println(favoriteNumber.getOwnerName() + " " + greeting);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.otus.example.beanslifecycledemo.domain;
|
||||
|
||||
public abstract class PhoneNumber {
|
||||
public String getOwnerName() {
|
||||
return "Спорт-лото";
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package ru.otus.example.beanslifecycledemo.lifecycle;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.BeanNameGenerator;
|
||||
import org.springframework.beans.factory.support.GenericBeanDefinition;
|
||||
import org.springframework.context.EnvironmentAware;
|
||||
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
|
||||
public class CustomBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {
|
||||
private Environment environment;
|
||||
|
||||
@Override
|
||||
public void setEnvironment(Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
|
||||
BeanDefinitionRegistry registry,
|
||||
BeanNameGenerator importBeanNameGenerator) {
|
||||
registerBeanDefinitions(importingClassMetadata, registry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerBeanDefinitions(AnnotationMetadata metadata,
|
||||
BeanDefinitionRegistry registry) {
|
||||
|
||||
registerBeanFactoryPostProcessor(registry);
|
||||
registerBeanPostProcessor(registry);
|
||||
|
||||
if (Optional.ofNullable(environment.getProperty("lifecycle.print.enabled", Boolean.class)).orElse(false)) {
|
||||
System.out.println("Шаг #0: ImportBeanDefinitionRegistrar.registerBeanDefinitions\n");
|
||||
registerCustomLifeCycleBean(registry);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void registerCustomLifeCycleBean(BeanDefinitionRegistry registry) {
|
||||
GenericBeanDefinition gbd = new GenericBeanDefinition();
|
||||
gbd.setBeanClass(CustomLifeCycleBean.class);
|
||||
gbd.setInitMethodName("customInitMethod");
|
||||
gbd.setDestroyMethodName("customDestroyMethod");
|
||||
registry.registerBeanDefinition("customLifeCycleBean", gbd);
|
||||
}
|
||||
|
||||
private void registerBeanFactoryPostProcessor(BeanDefinitionRegistry registry) {
|
||||
GenericBeanDefinition gbd = new GenericBeanDefinition();
|
||||
gbd.setBeanClass(CustomBeanFactoryPostProcessor.class);
|
||||
registry.registerBeanDefinition("customBeanFactoryPostProcessor", gbd);
|
||||
}
|
||||
|
||||
private void registerBeanPostProcessor(BeanDefinitionRegistry registry) {
|
||||
GenericBeanDefinition gbd = new GenericBeanDefinition();
|
||||
gbd.setBeanClass(CustomBeanPostProcessor.class);
|
||||
registry.registerBeanDefinition("customBeanPostProcessor", gbd);
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package ru.otus.example.beanslifecycledemo.lifecycle;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
|
||||
public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
|
||||
|
||||
private static final String CLASS_NAME_ATTR = "className";
|
||||
|
||||
@Override
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
|
||||
|
||||
if (beanFactory.containsBean("customLifeCycleBean")) {
|
||||
System.out.println("Шаг #1: BeanFactoryPostProcessor.postProcessBeanFactory\n");
|
||||
}
|
||||
|
||||
/* for (String beanName : beanFactory.getBeanDefinitionNames()) {
|
||||
var d = beanFactory.getBeanDefinition(beanName);
|
||||
if (d instanceof ScannedGenericBeanDefinition scannedBeanDefinition) {
|
||||
|
||||
if (!GirlfiendPhoneNumber.class.getName().equalsIgnoreCase(d.getBeanClassName())) {
|
||||
continue;
|
||||
}
|
||||
d.setBeanClassName(FriendPhoneNumber.class.getName());
|
||||
var classNameAttr = new BeanMetadataAttribute(CLASS_NAME_ATTR, FriendPhoneNumber.class.getName());
|
||||
scannedBeanDefinition.addMetadataAttribute(classNameAttr);
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package ru.otus.example.beanslifecycledemo.lifecycle;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.InvalidPropertyException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
|
||||
import ru.otus.example.beanslifecycledemo.domain.Phone;
|
||||
|
||||
public class CustomBeanPostProcessor implements BeanPostProcessor {
|
||||
|
||||
public static final String GREETING_PROPERTY = "greeting";
|
||||
|
||||
@Override
|
||||
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean.getClass().equals(CustomLifeCycleBean.class)) {
|
||||
System.out.println("Шаг #5: BeanPostProcessor.postProcessBeforeInitialization\n");
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
|
||||
if (bean.getClass().equals(CustomLifeCycleBean.class)) {
|
||||
System.out.println("Шаг #9: BeanPostProcessor.postProcessAfterInitialization\n");
|
||||
}
|
||||
|
||||
/*
|
||||
if (bean.getClass().isAssignableFrom(Phone.class)) {
|
||||
updateGreeting(bean);
|
||||
}
|
||||
*/
|
||||
return bean;
|
||||
}
|
||||
|
||||
private void updateGreeting(Object bean) {
|
||||
Class<?> aClass = Phone.class;
|
||||
try {
|
||||
Field greetingField = aClass.getDeclaredField(GREETING_PROPERTY);
|
||||
|
||||
greetingField.setAccessible(true);
|
||||
greetingField.set(bean, "Ай-да в гараж. Стихи читать!");
|
||||
} catch (Exception e) {
|
||||
throw new InvalidPropertyException(Phone.class, GREETING_PROPERTY,
|
||||
"Bean class does not have expected property", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package ru.otus.example.beanslifecycledemo.lifecycle;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
public class CustomLifeCycleBean implements InitializingBean, DisposableBean, BeanNameAware,
|
||||
BeanFactoryAware, ApplicationContextAware {
|
||||
|
||||
@Override
|
||||
public void setBeanName(String s) {
|
||||
System.out.println("Шаг #2: BeanNameAware\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
|
||||
System.out.println("Шаг #3: BeanFactoryAware\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
System.out.println("Шаг #4: ApplicationContextAware\n");
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void postConstruct() {
|
||||
System.out.println("Шаг #6: @PostConstruct\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
System.out.println("Шаг #7: InitializingBean.afterPropertiesSet\n");
|
||||
}
|
||||
|
||||
public void customInitMethod() {
|
||||
System.out.println("Шаг #8: CustomLifeCycleBean.customInitMethod\n");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void preDestroy() {
|
||||
System.out.println("Шаг #10: @PreDestroy\n");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() throws Exception {
|
||||
System.out.println("Шаг #11: DisposableBean.destroy\n");
|
||||
}
|
||||
|
||||
public void customDestroyMethod() {
|
||||
System.out.println("Шаг #12: CustomLifeCycleBean.customDestroyMethod\n");
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package ru.otus.example.beanslifecycledemo.lifecycle;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
@Import(CustomBeanDefinitionRegistrar.class)
|
||||
@Configuration
|
||||
public class LifeCycleConfig {
|
||||
/*
|
||||
@Bean
|
||||
public BeanFactoryPostProcessor customBeanFactoryPostProcessor() {
|
||||
return new CustomBeanFactoryPostProcessor();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BeanPostProcessor customBeanPostProcessor() {
|
||||
return new CustomBeanPostProcessor();
|
||||
}
|
||||
|
||||
@ConditionalOnProperty(name = "lifecycle.print.enabled", havingValue = "true")
|
||||
@Bean(initMethod = "customInitMethod", destroyMethod = "customDestroyMethod")
|
||||
public CustomLifeCycleBean customLifeCycleBean() {
|
||||
return new CustomLifeCycleBean();
|
||||
}
|
||||
*/
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
logging:
|
||||
level:
|
||||
root: ERROR
|
||||
|
||||
lifecycle:
|
||||
print:
|
||||
enabled: 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
|
||||
|
||||
- Расставить скоупы над сервисами так, чтобы приложение запустилось и заработало, как указано на
|
||||
странице http://localhost:8080
|
||||
- Подсказки в названии сервисов
|
||||
- Не забываем про proxyMode для некоторых скоупов
|
||||
|
||||
```
|
||||
Задать скоуп можно с помощью аннотации @Scope
|
||||
Возможные значения: singleton, prototype, session, request
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
<?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>3.4.2</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>ru.otus.example</groupId>
|
||||
<artifactId>beans-scopes-exercise</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<snakeyaml.version>2.0</snakeyaml.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package ru.otus.example.beansscopesdemo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class BeansScopesDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
var ctx = SpringApplication.run(BeansScopesDemoApplication.class, args);
|
||||
var serverPort = ctx.getEnvironment().getProperty("local.server.port");
|
||||
System.out.printf("Чтобы смотреть результат переходи сюда: http://localhost:%s", serverPort);
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package ru.otus.example.beansscopesdemo.controllers;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import ru.otus.example.beansscopesdemo.services.GreetingService;
|
||||
|
||||
@Controller
|
||||
public class GreetingController {
|
||||
private final GreetingService singletonGreetingService;
|
||||
private final GreetingService prototypeGreetingService1;
|
||||
private final GreetingService prototypeGreetingService2;
|
||||
private final GreetingService sessionGreetingService;
|
||||
private final GreetingService requestGreetingService;
|
||||
|
||||
public GreetingController(GreetingService singletonGreetingService,
|
||||
@Qualifier("prototypeGreetingService")
|
||||
GreetingService prototypeGreetingService1,
|
||||
@Qualifier("prototypeGreetingService")
|
||||
GreetingService prototypeGreetingService2,
|
||||
GreetingService sessionGreetingService,
|
||||
GreetingService requestGreetingService
|
||||
) {
|
||||
this.singletonGreetingService = singletonGreetingService;
|
||||
this.prototypeGreetingService1 = prototypeGreetingService1;
|
||||
this.prototypeGreetingService2 = prototypeGreetingService2;
|
||||
this.sessionGreetingService = sessionGreetingService;
|
||||
this.requestGreetingService = requestGreetingService;
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public String greetingPage(Model model) {
|
||||
model.addAttribute("singletonGreeting", singletonGreetingService.greeting());
|
||||
model.addAttribute("sessionGreeting", sessionGreetingService.greeting());
|
||||
model.addAttribute("requestGreeting", requestGreetingService.greeting());
|
||||
model.addAttribute("prototype1Greeting", prototypeGreetingService1.greeting());
|
||||
model.addAttribute("prototype2Greeting", prototypeGreetingService2.greeting());
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public abstract class AbstractGreetingServiceImpl implements GreetingService {
|
||||
|
||||
private final AtomicInteger counter;
|
||||
|
||||
public AbstractGreetingServiceImpl() {
|
||||
this.counter = new AtomicInteger(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String greeting() {
|
||||
return currentGreeting();
|
||||
}
|
||||
|
||||
private String currentGreeting() {
|
||||
return String.format("Привет! Это наша встреча №%d. Меня зовут: %s",
|
||||
counter.incrementAndGet(), Integer.toHexString(hashCode()));
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
public interface GreetingService {
|
||||
String greeting();
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service("prototypeGreetingService")
|
||||
public class PrototypeGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service("requestGreetingService")
|
||||
public class RequestGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service("sessionGreetingService")
|
||||
public class SessionGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service("singletonGreetingService")
|
||||
public class SingletonGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
server:
|
||||
port: 8081
|
||||
logging:
|
||||
level:
|
||||
root: ERROR
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Advanced configuration demo</title>
|
||||
<style>
|
||||
body {
|
||||
font-size: 16pt;
|
||||
}
|
||||
|
||||
h3 {
|
||||
color: CornflowerBlue;
|
||||
}
|
||||
|
||||
li {
|
||||
color: DarkGray;
|
||||
}
|
||||
|
||||
p {
|
||||
color: OrangeRed;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
<h3>Демонстрация @Scope</h3>
|
||||
<ul>
|
||||
<li>Singleton должен постоянно накручивать счетчик встреч и не менять имя</li>
|
||||
<li>Prototype1 должен вести себя так же, как и Singleton, но иметь имя отличное от Prototype2</li>
|
||||
<li>Prototype2 должен вести себя так же, как и Singleton, но иметь имя отличное от Prototype1</li>
|
||||
<li>Session должен вести себя как Singleton, но только до перезапуска браузера. После, счетчик встреч должен пойти
|
||||
заново
|
||||
</li>
|
||||
<li>Request должен всегда показывать первую встречу и разное имя</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<hr/>
|
||||
|
||||
<p th:text="'Singleton сказал: ' + ${singletonGreeting}"></p>
|
||||
<p th:text="'Prototype1 сказал: ' + ${prototype1Greeting}"></p>
|
||||
<p th:text="'Prototype2 сказал: ' + ${prototype2Greeting}"></p>
|
||||
<p th:text="'Session сказал: ' + ${sessionGreeting}"></p>
|
||||
<p th:text="'Request сказал: ' + ${requestGreeting}"></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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,15 @@
|
||||
#### Решение к упражнению №1
|
||||
|
||||
@Scope("singleton")
|
||||
SingletonGreetingServiceImpl
|
||||
|
||||
@Scope("prototype")
|
||||
PrototypeGreetingServiceImpl
|
||||
|
||||
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
|
||||
RequestGreetingServiceImpl
|
||||
|
||||
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
|
||||
SessionGreetingServiceImpl
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?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>3.4.2</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>ru.otus.example</groupId>
|
||||
<artifactId>beans-scopes-solution</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
<snakeyaml.version>2.0</snakeyaml.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.yaml</groupId>
|
||||
<artifactId>snakeyaml</artifactId>
|
||||
<version>${snakeyaml.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package ru.otus.example.beansscopesdemo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class BeansScopesDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
var ctx = SpringApplication.run(BeansScopesDemoApplication.class, args);
|
||||
var serverPort = ctx.getEnvironment().getProperty("local.server.port");
|
||||
System.out.printf("Чтобы смотреть результат переходи сюда: http://localhost:%s", serverPort);
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package ru.otus.example.beansscopesdemo.controllers;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import ru.otus.example.beansscopesdemo.services.GreetingService;
|
||||
|
||||
@Controller
|
||||
public class GreetingController {
|
||||
private final GreetingService singletonGreetingService;
|
||||
private final GreetingService prototypeGreetingService1;
|
||||
private final GreetingService prototypeGreetingService2;
|
||||
private final GreetingService sessionGreetingService;
|
||||
private final GreetingService requestGreetingService;
|
||||
|
||||
public GreetingController(GreetingService singletonGreetingService,
|
||||
@Qualifier("prototypeGreetingService")
|
||||
GreetingService prototypeGreetingService1,
|
||||
@Qualifier("prototypeGreetingService")
|
||||
GreetingService prototypeGreetingService2,
|
||||
GreetingService sessionGreetingService,
|
||||
GreetingService requestGreetingService
|
||||
) {
|
||||
this.singletonGreetingService = singletonGreetingService;
|
||||
this.prototypeGreetingService1 = prototypeGreetingService1;
|
||||
this.prototypeGreetingService2 = prototypeGreetingService2;
|
||||
this.sessionGreetingService = sessionGreetingService;
|
||||
this.requestGreetingService = requestGreetingService;
|
||||
}
|
||||
|
||||
@GetMapping("/")
|
||||
public String greetingPage(Model model) {
|
||||
model.addAttribute("singletonGreeting", singletonGreetingService.greeting());
|
||||
model.addAttribute("sessionGreeting", sessionGreetingService.greeting());
|
||||
model.addAttribute("requestGreeting", requestGreetingService.greeting());
|
||||
model.addAttribute("prototype1Greeting", prototypeGreetingService1.greeting());
|
||||
model.addAttribute("prototype2Greeting", prototypeGreetingService2.greeting());
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public abstract class AbstractGreetingServiceImpl implements GreetingService {
|
||||
|
||||
private final AtomicInteger counter;
|
||||
|
||||
public AbstractGreetingServiceImpl() {
|
||||
this.counter = new AtomicInteger(0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String greeting() {
|
||||
return currentGreeting();
|
||||
}
|
||||
|
||||
private String currentGreeting() {
|
||||
return String.format("Привет! Это наша встреча №%d. Меня зовут: %s",
|
||||
counter.incrementAndGet(), Integer.toHexString(hashCode()));
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
public interface GreetingService {
|
||||
String greeting();
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Scope(scopeName = "prototype")
|
||||
@Service("prototypeGreetingService")
|
||||
public class PrototypeGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.annotation.ScopedProxyMode;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
|
||||
@Service("requestGreetingService")
|
||||
public class RequestGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.context.annotation.ScopedProxyMode;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
|
||||
@Service("sessionGreetingService")
|
||||
public class SessionGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package ru.otus.example.beansscopesdemo.services;
|
||||
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Scope("singleton")
|
||||
@Service("singletonGreetingService")
|
||||
public class SingletonGreetingServiceImpl extends AbstractGreetingServiceImpl {
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
server:
|
||||
port: 8081
|
||||
logging:
|
||||
level:
|
||||
root: ERROR
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Advanced configuration demo</title>
|
||||
<style>
|
||||
body {
|
||||
font-size: 16pt;
|
||||
}
|
||||
|
||||
h3 {
|
||||
color: CornflowerBlue;
|
||||
}
|
||||
|
||||
li {
|
||||
color: DarkGray;
|
||||
}
|
||||
|
||||
p {
|
||||
color: OrangeRed;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<p>
|
||||
<h3>Демонстрация @Scope</h3>
|
||||
<ul>
|
||||
<li>Singleton должен постоянно накручивать счетчик встреч и не менять имя</li>
|
||||
<li>Prototype1 должен вести себя так же, как и Singleton, но иметь имя отличное от Prototype2</li>
|
||||
<li>Prototype2 должен вести себя так же, как и Singleton, но иметь имя отличное от Prototype1</li>
|
||||
<li>Session должен вести себя как Singleton, но только до перезапуска браузера. После, счетчик встреч должен пойти
|
||||
заново
|
||||
</li>
|
||||
<li>Request должен всегда показывать первую встречу и разное имя</li>
|
||||
</ul>
|
||||
</p>
|
||||
|
||||
<hr/>
|
||||
|
||||
<p th:text="'Singleton сказал: ' + ${singletonGreeting}"></p>
|
||||
<p th:text="'Prototype1 сказал: ' + ${prototype1Greeting}"></p>
|
||||
<p th:text="'Prototype2 сказал: ' + ${prototype2Greeting}"></p>
|
||||
<p th:text="'Session сказал: ' + ${sessionGreeting}"></p>
|
||||
<p th:text="'Request сказал: ' + ${requestGreeting}"></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?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>beans-scopes-exercise</module>
|
||||
<module>beans-scopes-solution</module>
|
||||
<module>beans-lifecycle-exercise</module>
|
||||
</modules>
|
||||
</project>
|
||||
Reference in New Issue
Block a user