单纯测试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.SameNameBeanTest required 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());
}
}
完结!
实际上还有一个解决办法,@Primary。这个注解就是防止找到多个相同名称的Bean的时候优先使用被@Primary修饰的!
特殊说明: 上述文章均是作者实际操作后产出。烦请各位,请勿直接盗用!转载记得标注原文链接:www.zanglikun.com
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取全部资料 ❤
第三方平台不会及时更新本文最新内容。如果发现本文资料不全,可访问本人的Java博客搜索:标题关键字。以获取全部资料 ❤