Spring的@Bean注解使用

Spring的@Bean注解用于告诉方法产生一个Bean对象,然后这个Bean对象交给Spring容器管理,产生Bean对象的方法Spring只会调用一次,调用之后Spring会将这个Bean放入到自己的IOC容器中。

使用@Bean注解方法生成一个Bean对象:

package com.config.server.endpoint;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@Service
public class BeanTest {

    @Bean
    public  BeanTest getBean(){
        BeanTest bean = new BeanTest();
        System.out.println("调用方法:"+bean);
        return bean;
    }
}

启动Spring获取上下文对象,通过上下文对象拿到Bean对象:

package com.config.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.ApplicationContext;

@EnableConfigServer
@SpringBootApplication
public class ServerApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(ServerApplication.class, args);
        Object obj = context.getBean("getBean");
        System.out.println(obj);
        Object obj1 = context.getBean("getBean");
        System.out.println(obj1);
    }
}

输出结果是:

调用方法:com.config.server.endpoint.BeanTest@6a638c79
com.config.server.endpoint.BeanTest@6a638c79
com.config.server.endpoint.BeanTest@6a638c79

默认Bean的名称就是方法的名称,不过也可以指定Bean的名称:

package com.config.server.endpoint;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@Service
public class BeanTest {

    @Bean(name = "my-bean-test")
    public  BeanTest getBean(){
        BeanTest bean = new BeanTest();
        System.out.println("调用方法:"+bean);
        return bean;
    }
}

使用@Bean注解的好处是能够动态的获取一个Bean对象,能够根据环境不同获取不同的Bean对象,或者是将其它的组件交给Spring容器管理。

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值