Spring @Bean 注解

春天@Bean注解应用于方法,用于指定它返回一个由Spring上下文管理的bean。Spring Bean注解通常在配置类方法中声明。在这种情况下,bean方法可以通过直接调用同一类中的其他@Bean方法来引用它们。

Spring @Bean示例

假设我们有一个简单的类如下。

package com.journaldev.spring;

public class MyDAOBean {

	@Override
	public String toString() {
		return "MyDAOBean"+this.hashCode();
	}
}

这是一个配置类,在其中为MyDAOBean类定义了一个@Bean方法。

package com.journaldev.spring;

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

@Configuration
public class MyAppConfiguration {

	@Bean
	public MyDAOBean getMyDAOBean() {
		return new MyDAOBean();
	}
}

我们可以使用下面的代码片段从Spring上下文中获取MyDAOBean bean。

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();
		
//按类获取Bean
MyDAOBean myDAOBean = context.getBean(MyDAOBean.class);

Spring Bean名称

我们可以指定@Bean名称并使用它从spring上下文中获取它们。假设我们有一个定义为:MyFileSystemBean的类。

package com.journaldev.spring;

public class MyFileSystemBean {

	@Override
	public String toString() {
		return "MyFileSystemBean"+this.hashCode();
	}
	
	public void init() {
		System.out.println("init method called");
	}
	
	public void destroy() {
		System.out.println("destroy method called");
	}
}

现在在配置类中定义一个@Bean方法:

@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"})
public MyFileSystemBean getMyFileSystemBean() {
	return new MyFileSystemBean();
}

我们可以通过使用bean名称从上下文中获取此bean。

MyFileSystemBean myFileSystemBean = (MyFileSystemBean) context.getBean("getMyFileSystemBean");

MyFileSystemBean myFileSystemBean1 = (MyFileSystemBean) context.getBean("MyFileSystemBean");

Spring @Bean initMethod 和 destroyMethod

我们还可以指定Spring bean的init方法和destroy方法。这些方法分别在创建Spring bean和关闭上下文时调用。

@Bean(name= {"getMyFileSystemBean","MyFileSystemBean"}, initMethod="init", destroyMethod="destroy")
public MyFileSystemBean getMyFileSystemBean() {
	return new MyFileSystemBean();
}

您会注意到在调用上下文的refresh方法时会调用“init”方法,而在调用上下文的close方法时会调用“destroy”方法。

总结

Spring @Bean 注解广泛用于基于注解的Spring应用程序。

您可以从我们的GitHub代码库下载完整的Spring项目。

Source:
https://www.digitalocean.com/community/tutorials/spring-bean-annotation