@Configuration和@Bean注解

@Configuration和@Bean注解,第1张

@Configuration和@Bean注解 @Configuration和@Bean 给容器添加bean组件

@Configuration属于 SpringBoot的 组件添加功能的注解

1、基本使用

Full模式与Lite模式

  • 配置 类组件之间无依赖关系用Lite模式加速容器启动过程,减少判断
  • 配置类组件之间有依赖关系,方法会被调用得到之前单实例组件,用Full模式
2、思考:SpringBoot怎么给容器中添加Bean组件?

在之前Spring的时候,我们都是用 xxx.xml 给bean注入

那么现在是
(1)@Configuration 告诉SpringBoot 这是一个配置类 == 配置 文件beans.xml
(2)@Bean 给容器中添加组件 == …

3、示例:
package com.spring.boot01helloworld2.config;

import ch.qos.logback.core.db.DBHelper;
import com.spring.boot01helloworld2.bean.Pet;
import com.spring.boot01helloworld2.bean.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.import;


@import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = true)
public class Myconfig {

    
    @Bean
    public User user01(){
        User zhangsan = new User("zhangsan",19);
        //user组件依赖了Pet组件,true是成立的
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }


    
    @Bean("tom")
    public Pet tomcatPet(){
        return new Pet("tomcat");
    }


}

总结:
  • @Configuration 代替了 之前Spring中 文件beans.xml
  • @Bean 代替了 在 beans.xml 中注册的 …

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5434228.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存