Spring5源码分析入门组件介绍

srping Bean的注册:

1.xml

2.@bean

3.@Conditional

 

xml创建bean的注册

beans.xml文件中用声明一个bean,id为这个bean的名字,声明bean的属性

从xml文件得到bean:

 @Bean注入

 这里@Configuration相当于xml文件里的beans,@bean声明bean,getFameBean就是这个bean的名字,获取bean是就是这个名字,@Value为属性赋值

这里@Lazy默认为true,

true:延迟加载,容器初始化的时候没有创建bean
false:容器初始化的时候bean
package com.sixstar.fame.exp01.config;import com.sixstar.fame.exp01.beans.FameBean01;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;/*** @Description: 配置类* @Author: 六星教育     Fame老师* @CreateDate: 2019/11/20$ 21:41$* @Version: 1.0*/
@Configuration    //  beans
public class FameConfig01 {/*** 默认true*      true:延迟加载,容器初始化的时候没有创建bean*      false:容器初始化的时候bean* @return*/@Lazy(false)@Bean("com.sixstar.fame.exp01.beans.FameBean01")  //  beanFameBean01 fameBean01(){System.out.println("给我们容器添加fameBean01");FameBean01 fameBean01 = new FameBean01();//   fameBean01.setName("Fame老师");//   fameBean01.setAge(18);return fameBean01;}
}

测试代码:

 

 /*** @Bean 注册*/@org.junit.Testpublic  void test02(){//  把配置类文件初始化到spring容器中ApplicationContext app = new AnnotationConfigApplicationContext(FameConfig01.class);System.out.println("spring容器初始化完成");//  从spring容器中获取beanFameBean01 fameBean01 = (FameBean01) app.getBean("com.sixstar.fame.exp01.beans.FameBean01");System.out.println(fameBean01);FameBean01 fameBean02 = app.getBean(FameBean01.class);System.out.println(fameBean02);System.out.println(fameBean01 == fameBean02);}输出结果:
给我们容器添加fameBean01
spring容器初始化完成
FameBean01{name='Fame老师', age=18}
FameBean01{name='Fame老师', age=18}
true

包扫描+标注注解

@ComponentScan扫描某个包下面的所有类
package com.stastar.fame.exp03.config;import com.stastar.fame.exp02.beans.ChineseBean;
import com.stastar.fame.exp02.beans.EnglishBean;
import com.stastar.fame.exp02.beans.LanggageBean;
import com.stastar.fame.exp02.config.ChineseCondition;
import com.stastar.fame.exp02.config.EnglishCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;/


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部