Advertisement
STANAANDREY

bean ex 1

Sep 1st, 2021
1,153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 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 Address {
  10.     private String street;
  11.     private int number;
  12.  
  13.     public Address(String street, int number) {
  14.         this.street = street;
  15.         this.number = number;
  16.     }
  17.  
  18.     public void setNumber(int number) {
  19.         this.number = number;
  20.     }
  21.  
  22.     public int getNumber() {
  23.         return number;
  24.     }
  25.  
  26.     public String getStreet() {
  27.         return street;
  28.     }
  29.  
  30.     public void setStreet(String street) {
  31.         this.street = street;
  32.     }
  33. }
  34.  
  35. @Component
  36. class Company {
  37.     private Address address;
  38.  
  39.     public Company(Address address) {
  40.         this.address = address;
  41.     }
  42.  
  43.     public void setAddress(Address address) {
  44.         this.address = address;
  45.     }
  46.  
  47.     public Address getAddress() {
  48.         return address;
  49.     }
  50. }
  51.  
  52. @ComponentScan(basePackageClasses = Company.class, excludeFilters = {
  53.         @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class)
  54. })
  55. class Config {
  56.     @Bean(name = "address")
  57.     public Address getAddress() {
  58.         return new Address("High Street", 1000);
  59.     }
  60. }
  61.  
  62. @SpringBootApplication
  63. public class DemoApplication {
  64.  
  65.     public static void main(String[] args) {
  66.         //SpringApplication.run(DemoApplication.class, args);
  67.         ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
  68.         Company asd = context.getBean("company", Company.class);
  69.     }
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement