专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 Spring@Bean注解

Spring@Bean注解

更新时间:2022-09-26 09:45:05 来源:赢咖4 浏览1011次

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

Spring @Bean示例

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

package com.journaldev.spring;
public class MyDAOBean {
	@Override
	public String toString() {
		return "MyDAOBean"+this.hashCode();
	}
}

这是一个配置类,我们为类定义了@Bean方法MyDAOBean。

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();
	}
}

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

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.journaldev.spring");
context.refresh();		
//Getting Bean by Class
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();
}

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

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>