通过@Resource获取@Bean注入的bean
首先了解一下@Resource注解和@Bean注解的作用
@Bean
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。作用为注册bean对象。
-
@Bean注解在返回实例的方法上,如果未通过@Bean指定bean的名称,则默认与标注的方法名相同; @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域; 既然@Bean的作用是注册bean对象,那么完全可以使用@Component、@Controller、@Service、@Ripository等注解注册bean,当然需要配置@ComponentScan注解进行自动扫描。
@Resource
作用:用来装配bean,可以写在字段上或者setter方法上。默认按照名称来装配注入,找不到名称时按照类型来装配注入。
获取bean
测试代码:
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
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的值
输入http://localhost:8080/index 即可看到如下结果。