栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@Configuration和@Bean注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@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 中注册的 …
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号