首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Spring@Bean注解

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; @Configurationpublic 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 ClassMyDAOBean 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方法。

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20230314A03CY000?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券