Spring @Bean注解详解

转自:

Spring @Bean注解详解

下文笔者将详细介绍@Bean注解的用法,如下所示:

@Bean注解的使用场景

@Bean注解常用于方法上,
   方法体中的内容代表此Bean实际产生的逻辑
   方法体的返回值为一个Bean
   这个Bean会交给Spring进行管理
   bean的命名通常采用 bean注解的方法名
注意事项:
   bean注解通常和Component或Configuration注解一起使用 
--------------------------------------------------------------
@Bean注解类似于xml中如下的bean定义 
<bean id="useService" class="com.test.service.UserServiceImpl"/>

@Bean注解的示例

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean
    public User user() {
        return new User;
    }
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class UserController {
    @Autowired
    User user;
 
    @GetMapping("/test")
    public User test() {
        return user.test();
    }
}

上述的Spring容器中,会生成一个名称为user的bean

例2:指定bean名称

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean(name = "javaUser")
    public User user() {
        return new User;
    }
}

//采用以下命名方式后
//bean可使用 user,javaUser,maomaoUser中任意一个名称可都
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyConfigration {
    @Bean(name = {"javaUser", "maomaoUser"})
    public User user() {
        return new User;
    }
}

Bean初始化和销毁示例演示

public class MyBean {
    public void init() {
        System.out.println("MyBean初始化...");
    }
 
    public void destroy() {
        System.out.println("MyBean销毁...");
    }
 
    public String get() {
        return "MyBean使用...";
    }
}

@Bean(initMethod="init", destroyMethod="destroy")
public MyBean myBean() {
    return new MyBean();
}

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return new serviceImpl3();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值