1. 获取bean:
@Bean:ctx.getBean("person", Person.class);
@Bean(“personJson”):ctx.getBean("personJson", Person.class);
2. 括号里自定义bean名称(未定义默认是方法名)
@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);
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 hi@niewj.com