SpringBoot相同BeanName & @Bean注解使用

单纯测试2个相同Bean 导致报错!

// Bean name 要与value保持一致 不然回报错哦
    @Bean(name = "redisson1",value = "redisson1")
    public Redisson redisson001() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    @Bean(name = "redisson2",value = "redisson2")
    public Redisson redisson002() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(1);
        return (Redisson) Redisson.create(config);
    }

    @Autowired
    private Redisson redisson;

(上文代码)启动项目报错信息

***************************
APPLICATION FAILED TO START
***************************

Description:

Field redisson in com.XXX.XXX.controller.SameNameBeanTestrequired a single bean, but 2 were found:
	- redisson1: defined by method 'redisson001' 
	- redisson2: defined by method 'redisson002' 

正常代码

import cn.hutool.core.date.DateTime;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author : zanglikun
 * @date : 2021/12/22 10:48
 * @Version: 1.0
 * @Desc : @Bean的同名处理
 */
@RestController
@RequestMapping("redis")
public class SameNameBeanTest {

    // Bean name 要与value保持一致 不然回报错哦@Bean(name = "redisson1", value = "redisson1")
    public Redisson redisson001() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    @Bean(name = "redisson2", value = "redisson2")
    public Redisson redisson002() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(1);
        return (Redisson) Redisson.create(config);
    }


    /**
     * Redisson1
     */
    @Autowired()
    @Qualifier(value = "redisson1")
    private Redisson redisson1;

    @GetMapping("redis001")
    public void redis001() {
        redisson1.getBucket("Redis001").set(new DateTime());
    }


    /**
     * Redisson2
     */
    @Resource(name = "redisson2")
    private Redisson redisson2;

    @GetMapping("redis002")
    public void redis002() {
        redisson2.getBucket("Redis002").set(new DateTime());
    }

}
SpringBoot相同BeanName & @Bean注解使用_第1张图片

完结!

实际上还有一个解决办法,@Primary。这个注解就是防止找到多个相同名称的Bean的时候优先使用被@Primary修饰的!

特殊说明: 以上文章,均是我实际操作,写出来的笔记资料,不会盗用别人文章!烦请各位,请勿直接盗用!转载记得标注来源!
收_心
永久会员
打赏 收藏 海报 链接

你可能感兴趣的:(spring,boot,java,spring,redis,后端)