@Configuration配置 @Bean

@Configuration 和 @Bean

  • @Configuration 用于定义配置类,作用在类上。

  • @Bean 用于定义 Bean对象,作用在方法上。

@Configration 注解类中可以声明一个或多个 @Bean 方法

User 类

public class User {

    private String name;

    private int age;
    
    //忽略getter、setter
}

Configuration 配置类

使用 @Bean 定义Bean,名称默认为方法名,也可以自定义。

比如方法名为 user,那么 @Bean的默认名称为 user,而 @Bean("user1")自定义 Bean的名称为 user1。

一般情况下,定义的Bean名称尽量和方法名保持一致。

@Configuration
public class MyConfiguration {

   /**
     * 定义Bean的名称为 user1
     *
     */
    @Bean("user1")
    public User user() {
        User user = new User();
        user.setAge(18);
        user.setName("John");
        return user;
    }

}

注入Bean

配置好了 Bean之后,就可以在其他Service里面注入了。

示例:

@Service
public class UserService {

    /**
     * 注入名称为 user1 的 User 对象。
     */
    @Resource(name = "user1")
    private User user;

    public User getUser() {
        System.out.println("getUser :"+ user);
        return user;
    }

}

参考资料

https://blog.csdn.net/weixin_45755816/article/details/121424751

posted on   乐之者v  阅读(115)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2017-06-15 At least one JAR was scanned for TLDs yet contained no TLDs.
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示