spring boot中的bean
@Test
public void getBean(){
HelloController bean = (HelloController) applicationContext.getBean("helloController");
System.out.println(bean);
HelloController bean1 = applicationContext.getBean(HelloController.class);
System.out.println(bean1);
HelloController bean2=applicationContext.getBean("helloController", HelloController.class);
System.out.println(bean2);
}
---------------------------------------------
注意点:
Spring 默认的 bean 名称是 类名首字母小写,即:
HelloController → helloController
-------------------------------------------
bean默认是单例的,如果想要bean变成多例的,需要使用@scope("prototype")注解;
---------------------------------------------------------
如果要引入第三方的bean不是自己写的,将其放入ioc容器中管理,需要用到@bean注解;
例如:
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
log.info("开始创建redis模板对象");
RedisTemplate redisTemplate = new RedisTemplate();
//设置redis的连接工厂对象
redisTemplate.setConnectionFactory(redisConnectionFactory);
//设置redis的序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
--------------------------------
可以通过@bean注解的name/value属性指定bean的名称,如果未指定bean的名字,就默认是方法名首字母小写;
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Hexo!

