Spring的@Bean注解使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/84347822

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容器管理。

猜你喜欢

转载自blog.csdn.net/yaomingyang/article/details/84347822