一、@Scope设置bean作用域,常用配置singleton(默认)、prototype,单例和原型,
singleton bean在容器启动就创建好,使用直接拿,prototype容器启动不会创建,使用时才创建
用例:
@Configuration public class ConfigurationBean { @Scope(value="singleton") @Bean("person") public Person getPerson() { Person person = new Person(); person.setAge(25); person.setName("小东"); System.out.println("person创建...."); return person; } }
二、懒加载
仅针对单实例bean 即singleton作用域bean,添加了@lazy注解,则容器创建时不创建bean,使用时才创建
@Configuration public class ConfigurationBean { @Lazy @Scope(value="singleton") @Bean("person") public Person getPerson() { Person person = new Person(); person.setAge(25); person.setName("小东"); System.out.println("person创建...."); return person; } }
三、@Conditional条件限定注解
用于限制某个类或方法创建的bean的限制条件
@Configuration public class ConfigurationBean { @Scope(value="singleton") @Bean("person") public Person getPerson() { Person person = new Person(); person.setAge(25); person.setName("小东"); return person; } @Conditional(value = MyConditional.class) @Bean("billGates") public Person getBillGates() { Person person = new Person(); person.setAge(66); person.setName("billGates"); return person; } }
public class MyConditional implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { BeanDefinitionRegistry registry = context.getRegistry(); String[] beanNames = registry.getBeanDefinitionNames(); System.out.println("registryBean : =" + beanNames); //打印容器注册所有bean Environment env = context.getEnvironment(); if("Windows 7".equals(env.getProperty("os.name"))) { Map<String, Object> map = metadata.getAnnotationAttributes("org.springframework.context.annotation.Bean"); String[] values = (String[]) map.get("value"); if("billGates".equals(values[0])) { return true; } } return false; } }
ApplicationContext applicationContext = new AnnotationConfigApplicationContext( ConfigurationBean.class); String[] beanNames = applicationContext.getBeanNamesForType(Person.class); for(String beanName : beanNames) { System.out.println("beanName:" + beanName); }
打印:
beanName:person
beanName:billGates