Drop Down

Saturday, September 21, 2019

Spring_App_8_JavaConfig

package com.amit.beans;

public class HelloBean
{
public HelloBean()
{
System.out.println("HelloBean Loanding....");
}
public String sayHello()
{
return "Message from HelloBean";
}

}

===================================================================
package com.amit.beans;

public class WelcomeBean  // Class of Bean needs to be mentioned in BeanConfiguration
{
public WelcomeBean()
{
System.out.println("WelcomeBean Loading.....");
}
public String getMsg() 
{
return "Message 1 from WelcomeBEAN";
}

}

====================================================================
package com.amit.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.amit.beans.HelloBean;
import com.amit.beans.WelcomeBean;

@Configuration   // optional
public class BeanConfiguration 
{
@Bean        //returned object in bean therefore declare @Bean
public WelcomeBean welcome_Bean() // id = welcome_Bean
{
return new WelcomeBean();
}
@Bean
public HelloBean helloBean()
{
return new HelloBean();
}

}

=====================================================================
package com.amit.Test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.amit.beans.HelloBean;
import com.amit.beans.WelcomeBean;
import com.amit.config.BeanConfiguration;

public class Test {

public static void main(String[] args) 
{
  ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
  WelcomeBean bean = (WelcomeBean)context.getBean("welcome_Bean");  //welcomeBean act like id (in classpathxmlApplicationcontext)
  String s = bean.getMsg();
  System.out.println("MSG: "+s);
  
  HelloBean bean2 = (HelloBean)context.getBean("helloBean");
  String s2 = bean2.sayHello();
  System.out.println("MSG: "+s2);
  
  
  
  
}

}

======================================================================

No comments:

Post a Comment

Java 8 Notes Pics