共计 930 个字符,预计需要花费 3 分钟才能阅读完成。
- 获取 bean:
@Bean:ctx.getBean("person", Person.class);
@Bean(“personJson”):ctx.getBean("personJson", Person.class);
- 括号里自定义 bean 名称: 如果没有定义, 默认是办法名 (person) : @Bean(“personJson”)
@Test
public void testBeanName() {AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ScopeConfig.class);
Arrays.stream(ctx.getBeanDefinitionNames()).forEach(System.out::println);
Person p = ctx.getBean("personJson", Person.class);
System.out.println(p);
}
package com.niewj.config;
import com.niewj.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
@Configuration
public class ScopeConfig {
/**
* singleton 单例默认是先初始化的; prototype 默认是提早初始化, 只有 getBean 才会初始化结构!
* singleton 单例的如果想提早初始化, 能够在 @Bean 同时加注解 @Lazy
* @return
*/
@Scope("singleton")
@Lazy
@Bean("personJson")
public Person person() {return new Person("json", 22);
}
}
正文完