您的位置:首页 > 其它

关于@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的值

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: