关于@Bean注解
2019-05-13 17:37
218 查看
传送门
https://www.jianshu.com/p/2f904bebb9d0
https://blog.csdn.net/badguy_gao/article/details/82853967
@Bean
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。作用为注册bean对象。
@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同;
@Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域;
既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。
@Resource
作用:用来装配bean,可以写在字段上或者setter方法上。默认按照名称来装配注入,找不到名称时按照类型来装配注入。
获取bean
测试代码:
[code]package com.example.demo.service; import com.example.demo.model.User; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; /** * @Author gaoyanliang * @Date 2018/9/25 15:56 **/ @Service public class DemoService { @Bean(name = "userDemo") public User getUser(){ User user = new User("gyl", "男", 22); return user; } }
首先用@Bean注入一个bean方法,名称为:userDemo
[code]package com.example.demo.controller; import com.example.demo.model.User; import com.example.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class UserController { @Resource(name = "userDemo") User user; @RequestMapping(value = "/index", method = RequestMethod.GET) public String index(){ return user.getName()+"--"+user.getSex()+"--"+user.getAge(); } }
通过@Resource获取名称为userDemo的值
相关文章推荐
- 关于service中添加Transaction注解后,service无法注入bean
- Spring 关于bean的获取以及自定义注解的起始注入和获取
- 关于使用注解出现BeanCreationException或者NameNotFoundException的解决方法
- 关于springmvc中注解@ModelAttribute的bean(对象参数)问题
- Spring中关于bean的注解的介绍
- Spring关于@Bean注解
- 关于spring的BeanFactory在使用注解的注解事项
- 关于spring mvc Controller的几个注解
- 关于Mybatis的研究之 bean没有set方法 也可以赋值
- struts2与spring集成时,关于Action类中成员bean自动注入的问题
- Spring 注解中,普通类获取@Service标记的方法 或者bean对象
- 关于Spring中配置LocalSessionFactoryBean来生成SessionFactory
- spring中配置Bean的xml方式和注解方式
- 关于spring中注解和xml混合使用
- spring注解:@ComponentScan,@Bean,@Import,@Component
- 关于Override在JDK1.5和JDK1.6上子类实现接口中方法使用@Override注解编译错误.
- spring 使用注解注入bean
- Spring的bean管理(注解)
- 关于PIX的配置及注解
- 关于spring boot无法自动注入bean问题解决方案