5、@scope注解
5.1、默认多实例,单实例
5.1.1、编写配置类
@Configuration @ComponentScan("com.sun") public class MainConfig2 { /** prototype 返回多实例 :在调用的时候才在容器中创建对象,没调用一次在IOC中创建一个对象 singleton 返回单实例:在IOC容器加载的时候就在容器中创建了对象 */ @Scope("prototype") //singleton @Bean public Person person(){ System.out.println("在IOC容器中创建对象"); return new Person("sun",11); } }
测试类:
@Test public void testIOC1(){ //获取容器中所有的bean 对象 ApplicationContext applicationContext=new AnnotationConfigApplicationContext(MainConfig2.class); System.out.println("在IOC容器中创建对象---1"); //可以发现多实例只有在调用的时候 Person person1 = applicationContext.getBean("person",Person.class);//测试单实例注释这里 Person person2 = applicationContext.getBean("person",Person.class);//测试单实例注释这里 }
结果:
在IOC容器中创建对象---1
在IOC容器中创建对象
在IOC容器中创建对象
5.4、懒加载
针对单实例设置,因为单实例是在容器启动时创建对象
懒加载就是不让单实例在容器启动时创建,在第一次获取Bean时创建对象并初始化。
只需要在方法上添加注解@Lazy
@Configuration // 告诉Spring这是一个配置类
@ComponentScan(value = "com.xjhqre")
public class MainConfig2 {@Bean("person")
@Lazy
public Person person() {
return new Person("张三", 25);
}}
6、@Conditional注解(重点)
按照一定的条件进行判断,满足条件给容器中注册Bean
6.1、业务场景
如果是linux系统则注册linus,如果是windows系统则注册bill Gates
6.2、编写WindowsCondition
编写windows条件,需要实现接口Condition,重写matches方法
public class ConfigWindos implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { Environment environment = conditionContext.getEnvironment(); String property = environment.getProperty("os.name"); if(property.contains("Windows")) { return true; } return false; } }
6.3、编写LinuxCondition
public class ConfigLinux implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { Environment environment = conditionContext.getEnvironment(); String property = environment.getProperty("os.name"); if(property.contains("linus")) { return true; } return false; } }
6.4、编写配置类
@Configuration @ComponentScan("com.sun") public class MainConfig2 { /** prototype 返回多实例 :在调用方法获取的时候才在容器中创建对象 singleton 返回单实例:在IOC容器加载的时候就在容器中创建了对象 */ @Scope("prototype") @Bean public Person person(){ System.out.println("在IOC容器中创建对象"); return new Person("sun",11); } @Conditional(ConfigWindos.class) //添加条件过滤 @Bean("windos") public Person person1(){ System.out.println("windos"); return new Person("windos",66); } @Conditional(ConfigLinux.class) @Bean("linux") public Person person2(){ System.out.println("linux"); return new Person("linux",56); } }
6.5、编写测试
@Test public void test3(){ String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class); Environment environment = applicationContext.getEnvironment(); String property = environment.getProperty("os.name"); System.out.println(property); Map<String, Person> beansOfType = applicationContext.getBeansOfType(Person.class); System.out.println(beansOfType); }
当@Conditional配置在类上时,表示只有满足条件时,这个配置类配置的所有bean才会生效