import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class BeanConfig
{
// Below @Bean annotation is used to create Student class Bean
@Bean
public Student stdId() // Here method name is the bean-id / bean-name
{
// It will return the Student object
return new Student();
}
}
2. Different ways to access Student Bean Object
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import in.sp.beans.Student;
import in.sp.config.AppConfig;
public class MainApp
{
public static void main(String[] args)
{
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// way 1 to get Student bean object
// Student std = context.getBean(Student.class);
// way 2 to get Student bean object
Student std = (Student) context.getBean("stdId");
std.display();
}
}
The @Bean annotation can be configured with additional parameters to customize the bean's behavior.
Below are several variations and examples :-
@Bean(name = "myService1")
public MyService myService()
{
return new MyService();
}
2. Different ways to access Student Bean Object
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// way 1 to get MyService bean object
MyService ms = context.getBean(MyService.class);
// way 2 to get MyService bean object
MyService ms = (MyService) context.getBean("myService1");
@Bean(name = {"myService1", "myService2", "myService3"})
public MyService myService()
{
return new MyService();
}
2. Different ways to access Student Bean Object
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
// way 1 to get MyService bean object
MyService ms = context.getBean(MyService.class);
// way 2 to get MyService bean object
MyService ms = (MyService) context.getBean("myService1");
// way 3 to get MyService bean object
MyService ms = (MyService) context.getBean("myService2");
// way 4 to get MyService bean object
MyService ms = (MyService) context.getBean("myService3");
import org.springframework.context.annotation.Scope;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // Creates a new instance each time
public MyService myService()
{
return new MyService();
}
@Bean(initMethod = "init", destroyMethod = "cleanup")
public MyService myService()
{
return new MyService();
}
import org.springframework.context.annotation.Conditional;
@Bean
@Conditional(MyCondition.class) // Only creates bean if MyCondition is met
public MyService myService()
{
return new MyService();
}
@Bean
public MyService myService(DependencyBean dependencyBean)
{
return new MyService(dependencyBean);
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.