Advertisement
STANAANDREY

bean ex 2

Sep 1st, 2021
1,222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.36 KB | None | 0 0
  1. package com.example.demo;
  2. import org.springframework.beans.factory.annotation.Required;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.annotation.*;
  7. import org.springframework.stereotype.Component;
  8.  
  9. class Tiger implements AnnotationConfig.Animal {
  10.     private String name;
  11.  
  12.     public Tiger(String name) {
  13.         this.name = name;
  14.     }
  15.  
  16.     public String getName() {
  17.         return name;
  18.     }
  19. }
  20.  
  21. class Lion implements AnnotationConfig.Animal {
  22.     private String name;
  23.  
  24.     public String getName() {
  25.         return name;
  26.     }
  27.  
  28.     public Lion(String name) {
  29.         this.name = name;
  30.     }
  31. }
  32.  
  33. @Configuration
  34. class AnnotationConfig {
  35.  
  36.     @Bean(name = {"tiger", "kitty"})
  37.     @Scope(value = "prototype")
  38.     Tiger getTiger(String name) {
  39.         return new Tiger(name);
  40.     }
  41.  
  42.     @Bean(name = "lion")
  43.     Lion getLion() {
  44.         return new Lion("Hardcoded lion name");
  45.     }
  46.  
  47.     interface Animal {}
  48. }
  49.  
  50. @SpringBootApplication
  51. public class DemoApplication {
  52.  
  53.     public static void main(String[] args) {
  54.         //SpringApplication.run(DemoApplication.class, args);
  55.         ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationConfig.class);
  56.         Tiger t =  (Tiger) context.getBean("tiger", "sherkan");
  57.         System.out.println(t.getName());//*/
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement