关于@Bean注解

传送门

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

测试代码:

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的值

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值