Java for Beginner
673 subscribers
541 photos
155 videos
12 files
827 links
Канал от новичков для новичков!
Изучайте Java вместе с нами!
Здесь мы обмениваемся опытом и постоянно изучаем что-то новое!

Наш YouTube канал - https://www.youtube.com/@Java_Beginner-Dev

Наш канал на RUTube - https://rutube.ru/channel/37896292/
Download Telegram
Что выведет код?

Задача на #Spring_Container, уровень сложный.

Решение будет опубликовано через 30 минут😉

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

public class Task181024_2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service1 = context.getBean(MyService.class);
MyService service2 = context.getBean(MyService.class);
System.out.println(service1 == service2);
System.out.println(service1.getDependencyMessage());
}
}

class MyService {
private final Dependency dependency;

public MyService(Dependency dependency) {
this.dependency = dependency;
}

public String getDependencyMessage() {
return dependency.getMessage();
}
}

class Dependency {
private final String message;

public Dependency(String message) {
this.message = message;
}

public String getMessage() {
return message;
}
}

@Configuration
class AppConfig {
@Bean
public MyService myService() {
return new MyService(dependency());
}

@Bean
@Scope("prototype")
public Dependency dependency() {
return new Dependency("Injected Dependency Message");
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Тема: #Spring_Configuration_Annotations. Сложность средняя.

Подробный разбор через 30 минут!🫡

import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

public class Task211024_2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfigTask.class);
MyServiceTest myService = context.getBean(MyServiceTest.class);
myService.printMessage();
}
}

@Component
class MyServiceTest {
private final MyRepository myRepository;
private final String prefix;

public MyServiceTest(MyRepository myRepository, @Value("CustomPrefix") String prefix) {
this.myRepository = myRepository;
this.prefix = prefix;
}

public void printMessage() {
System.out.println(prefix + ": " + myRepository.getData());
}
}

@Component
class MyRepository {
public String getData() {
return "Repository Data";
}
}

@Configuration
@ComponentScan()
class AppConfigTask {}


#TasksSpring
Что выведет код?

Задача по Spring. Тема: #Spring_Bean_LifeCicle. Сложность средняя.

Подробный разбор через 30 минут!🫡

public class Task221024_2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig221024.class);
MyBean myBean = context.getBean(MyBean.class);
myBean.doSomething();
context.close();
}
}

@Component
class MyBean implements InitializingBean, DisposableBean {

public MyBean() {
System.out.println("Constructor called");
}

@Override
public void afterPropertiesSet() {
System.out.println("afterPropertiesSet (init) called");
}

public void doSomething() {
System.out.println("Doing something");
}

@Override
public void destroy() {
System.out.println("destroy (cleanup) called");
}
}

@Configuration
@ComponentScan()
class AppConfig221024 {}


#TasksSpring
Что выведет код?

Задача по Spring. Тема: #Spring_Prototype и #Spring_Singleton. Сложность средняя.

Подробный разбор через 30 минут!🫡

import org.springframework.context.annotation.*;

@Configuration
class Config {
@Bean
@Scope("singleton")
public MyBean2310 singletonBean() {
return new MyBean2310("singleton");
}

@Bean
@Scope("prototype")
public MyBean2310 prototypeBean() {
return new MyBean2310("prototype");
}
}

class MyBean2310 {
public MyBean2310(String scope) {
System.out.println("MyBean created for "+scope);
}
}

public class Task231024_2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

MyBean2310 singleton1 = context.getBean("singletonBean", MyBean2310.class);
MyBean2310 singleton2 = context.getBean("singletonBean", MyBean2310.class);

MyBean2310 prototype1 = context.getBean("prototypeBean", MyBean2310.class);
MyBean2310 prototype2 = context.getBean("prototypeBean", MyBean2310.class);

context.close();
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Тема: #Dependency_Injection_via_setters и #Dependency_Injection_via_constructor. Сложность средняя.

Подробный разбор через 30 минут!🫡

import org.springframework.context.annotation.*;

@Configuration
class Config2410 {
@Bean
public MyService2410 myService2410() {
return new MyService2410();
}

@Bean
public MyBean2410 setterInjectedBean2410(MyService2410 myService) {
MyBean2410 bean = new MyBean2410();
bean.setMyService2410(myService);
return bean;
}

@Bean
public MyBean2410 constructorInjectedBean2410(MyService2410 myService) {
return new MyBean2410(myService);
}
}

class MyService2410 {
public void serve() {
System.out.println("Service called");
}
}

class MyBean2410 {
private MyService2410 myService;

public MyBean2410(MyService2410 myService) {
this.myService = myService;
System.out.println("Constructor injection");
}

public MyBean2410() {
System.out.println("No-arg constructor");
}

public void setMyService2410(MyService2410 myService) {
this.myService = myService;
System.out.println("Setter injection");
}

public void useService2410() {
myService.serve();
}
}

public class Task241024_2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config2410.class);

MyBean2410 setterBean = context.getBean("setterInjectedBean2410", MyBean2410.class);
MyBean2410 constructorBean = context.getBean("constructorInjectedBean2410", MyBean2410.class);

setterBean.useService2410();
constructorBean.useService2410();

context.close();
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Тема: #Autowired и #Qualifier. Сложность средняя.

Подробный разбор через 30 минут!🫡

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class Config2510 {
@Bean
public Service2510 serviceA() {
return new ServiceA2510();
}

@Bean
public Service2510 serviceB() {
return new ServiceB2510();
}

@Bean
public Client2510 client(@Qualifier("serviceA") Service2510 service) {
return new Client2510(service);
}
}

interface Service2510 {
void execute();
}

class ServiceA2510 implements Service2510 {
public void execute() {
System.out.println("Service A executed");
}
}

class ServiceB2510 implements Service2510 {
public void execute() {
System.out.println("Service B executed");
}
}

class Client2510 {
private Service2510 service;

@Autowired
public Client2510(@Qualifier("serviceA") Service2510 service) {
this.service = service;
}

public void run() {
service.execute();
}
}

public class Task251024_2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config2510.class);
Client2510 client = context.getBean(Client2510.class);
client.run();
context.close();
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Различия между BeanFactory и ApplicationContext. Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class Task281024_2 {
public static void main(String[] args) {
BeanFactory beanFactory = new AnnotationConfigApplicationContext(Config2810.class);
ApplicationContext appContext = new AnnotationConfigApplicationContext(Config2810.class);

Bean2810 beanFromFactory = (Bean2810) beanFactory.getBean("bean2810");
Bean2810 beanFromContext = (Bean2810) appContext.getBean("bean2810");

System.out.println(beanFromFactory == beanFromContext);
}
}

@Configuration
class Config2810 {
@Bean
public Bean2810 bean2810() {
return new Bean2810();
}
}

class Bean2810 {}


#TasksSpring
Что выведет код?

Задача по Spring. @Component и @Service. Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

public class Main301024_2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config3010.class);
Client3010 client = context.getBean(Client3010.class);
client.process();
}
}

@Configuration
@ComponentScan
class Config3010 {}

@Component
class Client3010 {
private final Service3010 service;

@Autowired
public Client3010(Service3010 service) {
this.service = service;
}

public void process() {
service.execute3010();
}
}

@Service
class Service3010 {
public void execute3010() {
System.out.println("Service executed");
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Аннотации @NotNull @Size @Email @Min @Max. Сложность легкая.

Подробный разбор через 30 минут!🫡

import jakarta.validation.ConstraintViolationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class Main311024_2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(Config3110.class);
UserService3110 userService = context.getBean(UserService3110.class);

try {
userService.registerUser("Jo", "mai.ru", 15);
} catch (ConstraintViolationException e) {
System.out.println("Validation failed");
}
}
}

@Configuration
class Config3110 {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}

@Bean
public UserService3110 userService3110() {
return new UserService3110();
}
}

@Component
@Validated
class UserService3110 {

public void registerUser(
@NotNull @Size(min = 3, message = "Name must be at least 3 characters") String name,
@Email(message = "Email should be valid") String email,
@Min(value = 16, message = "Age must be at least 16") int age) {

System.out.println("User registered: " + name + ", " + email + ", " + age);
}
}


#TasksSpring
Что выведет код?

Задача по Spring. Аннотации @Import и @Value Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

public class Main011124_2 {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig0111.class);
Client0111 client = context.getBean(Client0111.class);
client.printMessage();
}
}

@Configuration
@Import(ServiceConfig0111.class)
class MainConfig0111 {
@Bean
public Client0111 client0111(Service0111 service) {
return new Client0111(service);
}
}

@Configuration
class ServiceConfig0111 {
@Bean
public Service0111 service0111(@Value("${message:Hello, Spring}") String message) {
return new Service0111(message);
}
}

class Client0111 {
private final Service0111 service;

public Client0111(Service0111 service) {
this.service = service;
}

public void printMessage() {
System.out.println(service.message());
}
}

record Service0111(String message) {
}


#TasksSpring
Что выведет код при обращении к URL "/greet/John"?

Задача по Spring. Spring MVC. Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
public class Main041124_2 {
public static void main(String[] args) {
SpringApplication.run(Main041124_2.class, args);
}
}

@Controller
class GreetingController0411 {

@GetMapping("/greet/{name}")
@ResponseBody
public String greetUser(@PathVariable String name, @RequestParam(defaultValue = "Guest") String title) {
return "Hello, " + title + " " + name + "!";
}
}


#TasksSpring
Что выведет код при обращении к URL "/home/welcome"?

Задача по Spring. @Controller,@RequestMapping . Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@SpringBootApplication
public class Main051124_2 {
public static void main(String[] args) {
SpringApplication.run(Main051124_2.class, args);
}
}

@Controller
@RequestMapping("/home")
class HomeController0511 {

@RequestMapping("/welcome")
@ResponseBody
public String welcome() {
return "Welcome to the home page!";
}

@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "Hello from home!";
}
}


#TasksSpring
Что выведет код при обращении к URL "/user/register/John?age=25"?

Задача по Spring @GetMapping, @RequestBody, @ModelAttribute, @RequestParam и @PathVariable. Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
public class Main071124_2 {
public static void main(String[] args) {
SpringApplication.run(Main071124_2.class, args);
}
}

@Controller
@RequestMapping("/user")
class UserController0711 {

@GetMapping("/register/{name}")
@ResponseBody
public String registerUser(@PathVariable String name, @RequestParam int age, @ModelAttribute("status") String status) {
return "User: " + name + ", Age: " + age + ", Status: " + status;
}

@ModelAttribute("status")
public String status() {
return "Active";
}
}


#TasksSpring
Что выведет код при обращении к URL "/api/greet"?

Задача по Spring ViewResolver @RestControlle. Сложность легкая.

Подробный разбор через 30 минут!🫡

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@SpringBootApplication
public class Main081124_2 {
public static void main(String[] args) {
SpringApplication.run(Main081124_2.class, args);
}

@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}

@RestController
class ApiController0811 {

@GetMapping("/api/greet")
public String greet() {
return "Hello from API!";
}
}

@Controller
class ViewController0811 {

@GetMapping("/view/greet")
public String greetView() {
return "greeting";
}
}


#TasksSpring