Saturday, 2 July 2022

Spring Part 09 - @Bean

 Spring - @Bean

package com.ah.di;

import 
org.springframework.context.annotation.Bean;
import 
org.springframework.context.annotation.ComponentScan;
import 
org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class AppConf {

    
@Bean("car")
    
public Car carBean(){
        Car car = 
new Car();
        return 
car;
    
}
}


package com.ah.di;
import
org.springframework.beans.factory.annotation.Autowired;
public class
Car {
   
@Autowired     private Engine engine;
    public void
displayCarInfo(){         System.out.println("car class display method\n");
        if
(engine==null){             System.out.println("No engine object");         }else{             engine.testEngine();         }     }
}


package com.ah.di;
import
org.springframework.stereotype.Component;
@Component public class Engine {
   
public void testEngine(){         System.out.println("testEngine() method of 
Engine class")
    }
}


package com.ah.di;
import
org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class
Test {
   
public static void main(String[] args) {         ApplicationContext context =     new AnnotationConfigApplicationContext
(AppConf.class);
    var
carObj = context.getBean("car",Car.class);      carObj.displayCarInfo();
    
//displyAppContextBeanInfo(context);     }
   
public static void displyAppContextBeanInfo(ApplicationContext context ){          for(String bean : 
context.getBeanDefinitionNames()){
            System.out.println(bean);
        }
    }

}

                                                                   Watch Demo


No comments:

Post a Comment