Spring @Bean 注解与示例
Spring 中最重要的注解之一是@Bean 注解,它应用于方法以指定它返回一个由 Spring 上下文管理的 bean。 Spring Bean 注解通常在配置类方法中声明。这个注解也是spring核心框架的一部分。那么让我们通过一个示例项目来了解@Bean Annotation。
Prerequisite:
- Spring @ComponentScan Annotation with Example
- Spring @Configuration Annotation with Example
实施:项目
假设我们已经有一个Java项目,并且所有 Spring JAR 文件都导入到该项目中。现在让我们创建一个名为 College 的简单类,在该类中,我们有一个简单的方法。以下是学院的代码。 Java文件并使用@Component和@ComponentScan注解让我们创建这个大学类的bean。所以我们可以为学院写代码。 Java文件是这样的。
A. 档案:大学。Java
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Importing required classes
import org.springframework.stereotype.Component;
// Annotation
@Component("collegeBean")
// Class
public class College {
// Method
public void test()
{
// Print statement
System.out.println("Test College Method");
}
}
Java
// Java Program to Illustrate Configuration Class
package ComponetAnnotation;
// Importing required classes
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
@ComponentScan(basePackages = "BeanAnnotation")
// Class
public class CollegeConfig {
}
Java
// Java Program to Illustrate
// Configuration of College Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
// Class
public class CollegeConfig {
// Creating College class Bean
// using Bean annotation
@Bean
// Here the method name is the
// bean id/bean name
public College collegeBean()
{
// Returns the College class object
return new College();
}
}
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Main(Application) Class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Application(Main) class
public class Main {
// main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college = context.getBean("myCollegeBean",
College.class);
// Invoking the method
// inside main() method
college.test();
}
}
Java
// Java Program to Illustrate Principal Class
package BeanAnnotation;
// Class
public class Principal {
// Method
public void principalInfo()
{
// Print statement
System.out.println("Hi, I am your principal");
}
}
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
// Class data member
private Principal principal;
// Method
public void test()
{
principal.principalInfo();
// Print statement
System.out.println("Test College Method");
}
}
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
private Principal principal;
public College(Principal principal)
{
this.principal = principal;
}
public void test()
{
principal.principalInfo();
System.out.println("Test College Method");
}
}
Java
// Java Program to Illustrate Configuration Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
public class CollegeConfig {
// Creating the Bean for Principal Class
@Bean public Principal principalBean()
{
return new Principal();
}
@Bean public College collegeBean()
{
// Constructor Injection
return new College(principalBean());
}
}
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Main class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
// Class data members
private Principal principal;
// Setter
public void setPrincipal(Principal principal)
{
// this keywords refers to current instance itself
this.principal = principal;
}
// Method
public void test()
{
principal.principalInfo();
// Print statement
System.out.println("Test College Method");
}
}
Java
// Java Program to Illustrate Configuration Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
// Class
public class CollegeConfig {
// Creating the Bean for Principal Class
@Bean public Principal principalBean()
{
return new Principal();
}
@Bean public College collegeBean()
{
// Setter Injection
College college = new College();
college.setPrincipal(principalBean());
return college;
}
}
Java
// Java Program to Illustrate Application (Main) Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Application (Main) class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
现在让我们创建一个名为CollegeConfig的配置类。下面是CollegeConfig 的代码。Java
配置类
Java
// Java Program to Illustrate Configuration Class
package ComponetAnnotation;
// Importing required classes
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
@ComponentScan(basePackages = "BeanAnnotation")
// Class
public class CollegeConfig {
}
但是我们不想使用@Component和@ComponentScan注释来创建bean。让我们讨论另一种完成相同任务的方法。所以我们将使用@Bean 注解创建spring bean。要使用配置类中的@Bean 注解创建 Collge 类 bean,我们可以在CollegeConfig 中编写类似这样的内容。 Java文件。请参阅评论以获得更好的理解。
@Bean
// Here the method name is the
// bean id/bean name
public College collegeBean()
{
// Returns the College object
return new College();
}
B. 文件:CollegeConfig。Java
Java
// Java Program to Illustrate
// Configuration of College Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
// Class
public class CollegeConfig {
// Creating College class Bean
// using Bean annotation
@Bean
// Here the method name is the
// bean id/bean name
public College collegeBean()
{
// Returns the College class object
return new College();
}
}
Note: Whenever you are using the @Bean annotation to create the bean you don’t need to use the @ComponentScan annotation inside your configuration class.
现在检查我们的应用程序,让我们在 Main 类中创建一个 main 方法。下面是Main 的代码。 Java文件。代码中添加了注释以更详细地理解代码。
C. 应用类
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Main(Application) Class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
输出:
Test College Method
Tip: Now let’s remove the @Bean annotation before the collegeBean() method and run our program again and you can see we are going to get the “NoSuchBeanDefinitionException” exception
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'collegeBean' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:863)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1344)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:309)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:213)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1160)
at BeanAnnotation.Main.main(Main.java:15)
所以关键是要让collegeBean() 方法像bean 一样工作,您需要在该特定方法之前定义@Bean 注解。
提供不同的 Bean ID/Bean 名称
现在的问题是我们可以给这个collegeBean()方法一个不同的Bean ID吗?我们可以。我们可以像这样修改我们的代码。
// Annotation
@Bean(name = "myCollegeBean")
// Class
public College collegeBean()
{
return new College();
}
因此,每当您想测试您的应用程序时,您还必须更改您的Main。 Java文件变成这样的东西。
D. 应用类
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Application(Main) class
public class Main {
// main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college = context.getBean("myCollegeBean",
College.class);
// Invoking the method
// inside main() method
college.test();
}
}
为同一个 Bean 赋予多个名称
更有趣的事情是我们可以为这个特定的collegeBean() 方法赋予多个名称。因此,我们可以进一步修改我们的代码,如下所示。
@Bean(name = {"myCollegeBean", "yourCollegeBean"})
public College collegeBean()
{
return new College();
}
同样,您需要修改 Main.应用程序执行期间的Java文件。
使用 @Bean 注解的依赖注入
现在让我们讨论另一种情况。假设我们的 College 类中有一个名为 Principal 的依赖类,那么该怎么办?所以场景是这样的。我们有一个名为Principal 的类。 Java ,我们在其中定义了一个简单的方法。
例子
Java
// Java Program to Illustrate Principal Class
package BeanAnnotation;
// Class
public class Principal {
// Method
public void principalInfo()
{
// Print statement
System.out.println("Hi, I am your principal");
}
}
而我们的College.class是这样的
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
// Class data member
private Principal principal;
// Method
public void test()
{
principal.principalInfo();
// Print statement
System.out.println("Test College Method");
}
}
So now we want to do the dependency injection. So we can do it in 2 ways as listed later implemented as shown below:
- Constructor Dependency Injection (CDI)
- Setter Dependency Injection (SDI)
方式一:构造函数依赖注入(CDI)
在这种情况下,首先,让我们在 College 类中创建一个构造函数。所以我们修改了学院。 Java文件是
A. 大学班
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
private Principal principal;
public College(Principal principal)
{
this.principal = principal;
}
public void test()
{
principal.principalInfo();
System.out.println("Test College Method");
}
}
现在来到 CollegeConfig。 Java文件和修改后的CollegeConfig. Java在下面给出。请参阅评论以更好地理解。
B. 配置类
Java
// Java Program to Illustrate Configuration Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
public class CollegeConfig {
// Creating the Bean for Principal Class
@Bean public Principal principalBean()
{
return new Principal();
}
@Bean public College collegeBean()
{
// Constructor Injection
return new College(principalBean());
}
}
最后下面是Main 的代码。 Java文件。
C. 应用类
Java
// Java Program to Illustrate Application Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Main class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
输出:
Hi, I am your principal
Test College Method
方式二:Setter 依赖注入(SDI)
在这种情况下,首先,让我们在 College 类中创建一个 setter 方法。所以我们修改了学院。 Java文件如下:
A. 大学班
Java
// Java Program to Illustrate College Class
package BeanAnnotation;
// Class
public class College {
// Class data members
private Principal principal;
// Setter
public void setPrincipal(Principal principal)
{
// this keywords refers to current instance itself
this.principal = principal;
}
// Method
public void test()
{
principal.principalInfo();
// Print statement
System.out.println("Test College Method");
}
}
现在来到 CollegeConfig。 Java文件和修改后的CollegeConfig. Java给出如下:
B. 配置类
Java
// Java Program to Illustrate Configuration Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// Annotation
@Configuration
// Class
public class CollegeConfig {
// Creating the Bean for Principal Class
@Bean public Principal principalBean()
{
return new Principal();
}
@Bean public College collegeBean()
{
// Setter Injection
College college = new College();
college.setPrincipal(principalBean());
return college;
}
}
最后下面是Main 的代码。 Java文件。
C. 应用类
Java
// Java Program to Illustrate Application (Main) Class
package BeanAnnotation;
// Importing required classes
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
// Application (Main) class
public class Main {
// Main driver method
public static void main(String[] args)
{
// Using AnnotationConfigApplicationContext
// instead of ClassPathXmlApplicationContext
// because we are not using XML Configuration
ApplicationContext context
= new AnnotationConfigApplicationContext(
CollegeConfig.class);
// Getting the bean
College college
= context.getBean("collegeBean", College.class);
// Invoking the method
// inside main() method
college.test();
}
}
输出:
Hi, I am your principal
Test College Method